如何在考虑两个列表时随机选择一个列表中的项?
抱歉,我没能想出一个更好的标题。我的问题是我有两个列表,我想从第一个列表中随机挑选一个项目,并将其与第二个列表中的一个项目匹配,但这两个项目的索引不能相同(比如li1[3]不能和li2[3]匹配),而且一旦选中一个项目,它就必须从列表中移除。我试过这个代码,但它没有解决我的问题。谢谢大家的帮助。
from random import choice
teams1 = ["brazil", "croatia", "england", "italy", "mexico", "cameroon", "ivory coast", "japan"]
teams2 = ["spain", "germany", "belgium", "holland", "argentina", "portugal", "france", "usa"]
counter = 3
counter2 = 8
while counter != 0:
a = choice(range(1,counter2))
a1 = teams1[a]
b = choice(range(1,counter2))
b1 = teams2[b]
print(teams1[0], b1)
print(teams2[0], a1)
del teams1[a]
del teams2[b]
del teams1[0]
del teams2[0]
counter -= 1
counter2 -= 2
print(teams1[0], teams2[0])
3 个回答
1
我不会感到惊讶,如果有更优雅的方法来构建成对的组合,但这个方法似乎能满足问题评论中提到的要求:
#/usr/bin/env python2.7
from random import shuffle
def main():
teams1 = ["brazil", "croatia", "england", "italy",
"mexico", "cameroon", "ivory coast", "japan"]
teams2 = ["spain", "germany", "belgium", "holland",
"argentina", "portugal", "france", "usa"]
excluded_pairs = dict(zip(teams1, teams2))
shuffle(teams1) # not really needed
shuffle(teams2)
while len(teams1):
t1 = teams1.pop()
if len(teams1) > 1:
if teams2[-1] != excluded_pairs[t1]:
t2 = teams2.pop(-1)
else:
t2 = teams2.pop(-2)
elif len(teams1) == 0:
t2 = teams2.pop(-1)
elif len(teams1) == 1:
if (teams2[-1] != excluded_pairs[t1]
and teams2[-2] != excluded_pairs[teams1[0]]):
t2 = teams2.pop(-1)
else:
t2 = teams2.pop(-2)
print '{} vs. {}'.format(t1, t2)
print len(teams1)
print len(teams2)
if __name__ == '__main__':
main()
1
你可以使用 random.randrange
来实现这个功能!
import random
teams1 = ["brazil", "croatia", "england", "italy", "mexico", "cameroon", "ivory coast", "japan"]
teams2 = ["spain", "germany", "belgium", "holland", "argentina", "portugal", "france", "usa"]
t1 = random.randrange(0, len(teams1))
t2 = random.randrange(0, len(teams2))
while t2 == t1:
t2 = random.randrange(0, len(teams2))
rand_choice1 = teams1.pop(t1)
rand_choice2 = teams1.pop(t2)
这里的 while
循环是用来确保两个索引不一样,也就是说我们选出的两个队伍不会是同一个。然后,列表里的 .pop()
方法会把我们选择的队伍从列表中移除。
这种方法只会列出一场比赛,但其实可以很简单地把它做成一个函数,来随机匹配所有的队伍。
1
你的程序是对的。只是当两个列表中还有值的时候,你的程序就结束了。这是因为你的 counter
变成了 0,而这个条件:
while counter != 0:
就不再成立了。
你可以把这个条件改成检查两个列表中是否还有剩余的项目,使用:
while len(teams1) and len(teams2):
或者:
while counter > -1:
并且去掉最后一行:
print(teams1[0], teams2[0])
这样你的程序就能按预期工作了。