我是python的新手!
players = ["Matt","Joe", "Barry","Billy"]
numbers = [1,2,3,4]
def assignment(players, numbers):
for i in players:
for j in numbers:
print i,j
assignment(players,numbers)
我的尝试就在上面。
我想尝试回答=
Matt 1
Joe 2
Barry 3
Billy 4
但是每分钟给每个号码分配一个号码!关于如何解决这个问题的任何建议?
答案 0 :(得分:1)
使用zip
players = ["Matt","Joe", "Barry","Billy"]
numbers = [1,2,3,4]
for a in zip(players, numbers):
print(*a)
如果您的列表长度不同,zip
只会将另一个列表中具有相应索引的项目配对,如果您希望其他项目可以在python3中使用itertools.zip_longest
,指定python的fillvalue以填充空的项,例如:
from itertools import zip_longest
players = ["Matt","Joe", "Barry","Billy", "Johnson", "Riyad"]
numbers = [1,2,3,4]
for a in zip_longest(players, numbers, fillvalue=0):
print(*a)
输出
Matt 1
Joe 2
Barry 3
Billy 4
Johnson 0
Riyad 0
答案 1 :(得分:1)
def assignment(players, numbers):
for i, j in zip(players, numbers):
print i,j