随机分配2个for循环列表 [英] Randomize 2 lists for a for loop

查看:95
本文介绍了随机分配2个for循环列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个大小相同的列表以及以下代码:

Lets say I have 2 lists of the same size along with the following code:

list1 = ['tom', 'mary', 'frank', 'joe']
list2 = [1, 2, 3, 4]

for names, numbers in zip(list1, list2):
    print names, numbers

对于for循环的每次迭代,我如何使用每个列表中的随机索引?

How would I use a random index from each list for each iteration of the for loop?

如果我有2个大小不同的列表,则附上类似的注释:

Along a similar note, if I have 2 lists of different sizes:

list1 = ['tom', 'mary', 'frank', 'joe', 'john', 'barry']
list2 = [1, 2, 3, 4]

我如何像第一个示例一样使用随机索引,但是这次,一旦到达列表2之外的项目的第一个索引,就开始为列表1中的其余项目再次随机化列表2的索引?在这种情况下,zip不再是正确的方法了吗?

How do I, like the first example, use random indexes but this time, once it reaches the first index for the item that is outside list2, begin to randomize the index for list2 again for the remaining items in list1? Is zip no longer the correct method to use in this case?

frank 3
tom 4
john 2
mary 1
barry 4
joe 2

^所需的输出(但完全是随机的)

^desired output (but completely random)

推荐答案

这可行,但有点冗长:

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))

这篇关于随机分配2个for循环列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆