在Python中,我可以按索引号顺序打印3个列表吗?

2024-09-30 16:40:11 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有三个清单:

['this', 'is', 'the', 'first', 'list']
[1, 2, 3, 4, 5]
[0.01, 0.2, 0.3, 0.04, 0.05]

是否有方法允许我按索引顺序打印这些列表中的值?

例如

this, 1, 0.01 (all items at list[0])
is, 2, 0.2 (all items at list[1])
the, 3, 0.3 (all items at list[2])
first, 4, 0.04 (all items at list[3])
list, 5, 0.05 (all items at list[4])

每次运行脚本时,每个列表中的项目数都会有所不同,但它们最终的值总是相同的。因此,一次,脚本可以创建三个包含30个项的数组,另一次,它只能在每个数组中创建15个值,等等


Tags: the方法脚本列表顺序isitems数组
3条回答

使用zip

for items in zip(L1, L2, L3):
    print items

items将是一个元组,按顺序从每个列表中都有一个值。

lists = ( ['this', 'is', 'the', 'first', 'list'], 
          [1, 2, 3, 4, 5], 
          [0.01, 0.2, 0.3, 0.04, 0.05])
print zip(*lists)

将列表拉到一起,并在最短的列表用完项目时停止。

你可能要找的是zip

>>> x = ['this', 'is', 'the', 'first', 'list']
>>> y = [1, 2, 3, 4, 5]
>>> z = [0.01, 0.2, 0.3, 0.04, 0.05]
>>> zip(x,y,z)
[('this', 1, 0.01), ('is', 2, 0.20000000000000001), ('the', 3, 0.29999999999999999), ('first', 4, 0.040000000000000001), ('list', 5, 0.050000000000000003)]
>>> for (a,b,c) in zip(x,y,z):
...     print a, b, c
... 
this 1 0.01
is 2 0.2
the 3 0.3
first 4 0.04
list 5 0.05

相关问题 更多 >