我正试图将一个名字和姓氏列表结合起来,但没有运气。我的代码目前是这样的:
firstname=['Tom','Dick','Steve']
surname=['Johnson','Smith','Doe']
for f in (firstname):
for s in (surname):
print(f,s)
这给了我这样的东西:
Tom Johnson
Tom Smith
Tom Doe
Dick Johnson
依此类推,当我真正想要的时候:
Tom Johnson
Dick Smith
Steve Doe
非常感谢像我这样的初学者。
答案 0 :(得分:6)
for name, surname in zip(firstname, surname):
print(name, surname)
答案 1 :(得分:1)
Zip是在python中将两个列表组合在一起的方法。所以,作为一个函数,
def combine_names(first, last):
comb = zip(first, last)
for f,l in comb:
print f,l
答案 2 :(得分:0)
假设两个列表具有相同的长度,您可以迭代它并在两者上使用相应的索引:
for i in range(len(firstname)):
print (firstname[i], surname[i])
答案 3 :(得分:0)
firstname=['Tom','Dick','Steve']
surname=['Johnson','Smith','Doe']
i = 0
while i<min(len(firstname), len(surname)):
print (firstname[i], surname[j])
i += 1