python3 模拟swtich结构
在python中是没有swtich结构的,可以用字典配合lambda表达式实现:
import random
# 创建随机单词
l_store_word = ['one', 'two','three','four','five']
# 生成随机指定长度字符串
l_store_str = ['a','z','x','y','w']
d_random_style_string = {
# 随机一个随机单词random.choice(l_store_word)
# 随机一个随机字符串random.choice(l_store_str)
"1": lambda: random.choice(l_store_word) + '_' + random.choice(l_store_str),
# 随机组合
"2": lambda: random.choice(l_store_word) + random.choice(l_store_str),
"3": lambda: random.choice(l_store_word) + random.choice(l_store_str) + random.choice(l_store_word),
"4": lambda: random.choice(l_store_word) + random.choice(l_store_str) + random.choice(l_store_str),
# 随机组合+"_"
"5": lambda: \
random.choice(l_store_word) + '_' + random.choice(l_store_str) + '_' + random.choice(l_store_str),
"6": lambda: \
random.choice(l_store_word) + '_' + random.choice(l_store_str) + '_' + random.choice(l_store_str) + '_' \
+ random.choice(l_store_word),
"7": lambda: \
random.choice(l_store_word) + '_' + random.choice(l_store_str) + '_' + random.choice(l_store_word),
"8": lambda: \
random.choice(l_store_word) + '_' + random.choice(l_store_str) + '_' + random.choice(l_store_word) + '_' \
+ random.choice(l_store_str),
"9": lambda: \
random.choice(l_store_word) + '_' + random.choice(l_store_str) + '_' + random.choice(l_store_word) + '_' + \
random.choice(l_store_str) + "_" + random.choice(l_store_word)
}
i_random_int = random.randint(1, 9)
i_random_val = i_random_int % 10
# 最终name:从匿名的字典中随机返回一个
s_random_style_fixed_string = d_random_style_string.get(str(i_random_val))()
print(s_random_style_fixed_string)
浙公网安备 33010602011771号