假设我有2个相同大小的列表以及以下代码:
list1 = ['tom', 'mary', 'frank', 'joe']
list2 = [1, 2, 3, 4]
for names, numbers in zip(list1, list2):
print names, numbers
Run Code Online (Sandbox Code Playgroud)
对于for循环的每次迭代,我如何使用每个列表中的随机索引?
沿着类似的说明,如果我有2个不同大小的列表:
list1 = ['tom', 'mary', 'frank', 'joe', 'john', 'barry']
list2 = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
与第一个示例一样,我如何使用随机索引,但这次,一旦它到达list2之外的项目的第一个索引,就开始为list1中的剩余项目再次随机化list2的索引?在这种情况下,zip不再是正确的方法吗?
frank 3
tom 4
john 2
mary 1
barry 4
joe 2
Run Code Online (Sandbox Code Playgroud)
^期望的输出(但完全随机)
这有效,但有点冗长:
import random
def shuffled(seq):
copy = list(seq)
random.shuffle(copy)
return copy
def rand_repeat(seq):
while True:
for el in shuffled(seq):
yield el
list1 = ['tom', 'mary', 'frank', 'joe', 'john', 'barry']
list2 = [1, 2, 3, 4]
print zip(shuffled(list1), rand_repeat(list2))
Run Code Online (Sandbox Code Playgroud)