我是一个新手,我正在解决这个循环问题。我想随机将一个国家/地区分配给人员名单以进行抽奖竞赛。一旦分配了一个国家,那么它应该不再可用于循环的进一步迭代。循环应该遍历整个人员列表(比国家列表短)。是的,我知道代码可能更简单,但这只是我放弃的点。请指教!
import random
filez = open ('C:/Users/Andy/Desktop/countrys.txt', 'r')
countries = filez.readlines()
filez2 = open ('C:/Users/Andy/Desktop/names.txt', 'r' )
people = filez2.readlines()
def chop (x): #gets rid of wierd added bits
for i in range(0, len(x)):
x[i] = x[i] [:-1]
return x
chop(countries)
chop(people)
def assign (y):
used = []
for person in range(0, len(y)):
num = random.randint(0, len(countries))
if num not in used:
print (people[person] + " gets " + countries[num])
used.append(num)
else:
num = random.randint(0, len(countries))
print (people[person] + " gets " + countries[num])
used.append(num)
assign(people)
答案 0 :(得分:1)
可能的解决方案是:
random.shuffle(countries)
assignments = list(zip(people, countries))
这将为您提供(person, country)
元组的列表。