所以我有两个列表,一个Header 列表 和一个Client 列表:
标题列表 包含诸如
名字
或电话号码
之类的标题。客户列表 包含特定客户的详细信息,例如他们的名字或电话号码。
我试图一次打印每个列表的一部分。
例如:
First Name: Joe
Phone Number: 911
现在我有一个循环可以做一些接近我想要的事情
header_list = ['First Name: ',
'Last Name: ',
'Phone: ',
'City: ',
'State: ',
'Zip: ']
for elem in header_list:
print(elem)
for client in client_list[0]:
print (client)
break
这给出了类似的输出
First Name: Joe
Last Name: Joe
Phone Number: Joe
这个循环的问题在于它正确地打印出所有标题,但只打印出 client_list[0]
中的第一项,如果我删除中断然后它打印出 中的所有内容>client_list[0]
。
我将如何遍历 client_list[0]
获取列表中的第一个然后第二个等等?
最佳答案
您可以使用 zip
同时遍历 header 和值:
header_list = ['First Name: ', 'Last Name: ', 'Phone: ', 'City: ', 'State: ', 'Zip: ']
client_list = ['Joe', 'Somebody', '911']
for head, entry in zip(header_list, client_list):
print(head, entry)
输出:
First Name: Joe
Last Name: Somebody
Phone: 911
注意:较短的列表决定了您获得的迭代次数。
更长的客户列表:
header_list = ['First Name:', 'Last Name:', 'Phone:', 'City:', 'State:', 'Zip:']
client_list = ['Joe', 'Somebody', '911', 'Somewhere', 'AA', '012345']
for head, entry in zip(header_list, client_list):
print(head, entry)
打印:
First Name: Joe
Last Name: Somebody
Phone: 911
City: Somewhere
State: AA
Zip: 012345
旁注:无需在 header
中用空格填充字符串,print
会为您添加一个。
关于python - 如何在循环内遍历列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34191396/