简体   繁体   English

python遍历多个列表并返回random.choice

[英]python iterating through multiple lists and returning a random.choice

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

I want to iterate through separate lists returning a randomly chosen digit or letter from each and return a 'set' in this case of three unique letters or numbers. 我想遍历单独的列表,从每个列表中返回一个随机选择的数字或字母,并在这种情况下返回由三个唯一字母或数字组成的“集合”。 Caution the while loop does not work - this loops until it has returned all combinations, which I do not understand either. 注意while循环不起作用-循环直到返回所有组合为止,我也不明白。 Can I use random.choice(L1 or L2 or L3) to return x,y and z? 我可以使用random.choice(L1或L2或L3)返回x,y和z吗? Is there another simpler way to return a random selection from multiple lists? 还有另一种更简单的方法可以从多个列表中返回随机选择吗? THank you for your help 谢谢您的帮助

Something like? 就像是?

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM