import random
def iterate_thru_list():
i = 0
L1 = [1,2,3,4,5,6,7,8,9]
L2=['a','b','c','d','e','f','g','h','i']
L3= ['A','B','C','D','E','F','G','H','I']
random.shuffle(L1)
random.shuffle(L2)
random.shuffle(L3)
print ("List:")
while i <= 5:
for x, y, z in [(x,y,z) for x in L1 for y in L2 for z in L3]:
print(x,y,z)
i = i + 1
我想遍历单独的列表,从每个列表中返回一个随机选择的数字或字母,并返回一个“集合”,在这种情况下包含三个唯一的字母或数字。注意while循环不起作用 - 这会循环,直到它返回所有组合,我也不明白。我可以使用random.choice(L1或L2或L3)返回x,y和z吗?还有另一种更简单的方法可以从多个列表中返回随机选择吗? 谢谢你的帮助
答案 0 :(得分:4)
喜欢什么?
L1 = [1,2,3,4,5,6,7,8,9]
L2 = ['a','b','c','d','e','f','g','h','i']
L3 = ['A','B','C','D','E','F','G','H','I']
from random import choice
for i in range(5):
print list(map(choice, (L1, L2, L3)))
[4, 'h', 'A']
[7, 'b', 'G']
[3, 'c', 'C']
[6, 'f', 'H']
[5, 'b', 'A']