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

7 投票
4 回答
8596 浏览
提问于 2025-04-15 15:19

我有三个列表:

['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个值,等等。

4 个回答

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

把多个列表合并在一起,直到最短的那个列表里的东西用完为止。

3

使用 zip 函数

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

items 将会是一个元组,里面包含了每个列表中对应位置的值,顺序是一样的。

9

你可能在找的东西叫做 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

撰写回答