在Python中同时迭代两个列表

时间:2015-05-31 14:36:50

标签: python

假设我有以下内容:

cell_list = ['B1', 'B2', 'B3']
cell_data = ['1', '2', '3']

如何在Python中使用以下结果构建单个循环(可能是for循环)?

B1: 1
B2: 2
B3: 3

5 个答案:

答案 0 :(得分:1)

Python中用于同时迭代2个或更多个迭代的常用方法是使用zip函数,该函数创建元组列表。结果列表中的每个元组都包含每个可迭代的相应元素。

cell_list = ['B1', 'B2', 'B3']
cell_data = ['1', '2', '3']

for t in zip(cell_list, cell_data):
    print('%s: %s' % t)

<强>输出

B1: 1
B2: 2
B3: 3

如果您更喜欢使用更现代的print语法,请将打印行更改为:

print('{0}: {1}'.format(*t))

在2.6以上的Python版本中,您可以这样编写:

print('{}: {}'.format(*t))

答案 1 :(得分:0)

最简单的方法是zip列表并将dict应用于结果:

result = dict (zip (cell_list, cell_data))

话虽如此,如果您必须使用问题代码建议的for循环,您可以循环遍历列表并将其中一个视为潜在键,另一个视为潜在值:

result = {}
for i in range(len(cell_list)):
    result[cell_list[i]] = cell_data[i]

答案 2 :(得分:0)

for index in range(len(cell_list)) :
     print cell_list[index] + ": " + cell_data[index] 

请注意,此代码未经过我的手机发布测试。

这样做是因为它使用带有for循环的范围对象,所以它将迭代从0到列表长度的值。因此,由于列表是并行的,因此可以使用此索引在两个列表中打印项目。

答案 3 :(得分:0)

>>> cell_list = ['B1', 'B2', 'B3']
>>> cell_data = ['1', '2', '3']
>>> for a, b in zip(cell_list, cell_data):
       print '{0}: {1}'.format(a, b)


B1: 1
B2: 2
B3: 3

答案 4 :(得分:-1)

以下是使用for循环的解决方案:

for i in range(len(cell_list)):
    print (cell_list[i] + ": " + cell_data[i])