from random import *
prompt = "Enter a person participating.(end to exit):\n"
people = list(iter(lambda:input(prompt), "end"))
shuffle(people)
people.append(people[0])
for i in range(len(people) - 1):
print(people[i],"buys for", people[i + 1])
样品运行
Enter a person participating.(end to exit):
A
Enter a person participating.(end to exit):
B
Enter a person participating.(end to exit):
C
Enter a person participating.(end to exit):
end
A buys for B
B buys for C
C buys for A
你可以更换
people=[]
while True:
person=input("Enter a person participating.(end to exit):\n")
if person=="end": break
people.append(person)
和
prompt = "Enter a person participating.(end to exit):\n"
people = list(iter(lambda:input(prompt), "end"))
他们都在做同样的事情。iter
函数将继续执行我们作为第一个参数传递的函数,直到第二个值匹配。
然后,你这样做
people.append(people[0])
它是一个循环的东西,最后一个人必须为第一个人购买。append
将在最后插入。
for i in range(len(people) - 1):
我们这样做len(people) - 1
,因为如果n
有人,就会有n
购买。在这种情况下,我们在最后添加了第一个人,所以我们减去了一个。最后
print(people[i],"buys for", people[i + 1])
每个人都必须为列表中的下一个人购买。所以,people[i]
为people[i + 1]
.