如何使用索引打印列表中的元素?

时间:2016-04-03 20:49:42

标签: python

我正在尝试使用列表中每个元素的索引打印元素

但我的工具打印每个索引为0的元素和每个索引为1的元素,直到最后一个索引

任何人都可以解决它,我被困在这里了吗?

if __name__=="__main__":

    r = [6, 5, 3, 3]
    diff = [[(i,j)for i in r]for j in range(5)]
    print(diff)

实际输出:

[[(6, 0), (5, 0), (3, 0), (3, 0)], [(6, 1), (5, 1), (3, 1), (3, 1)], [(6, 2), (5, 2), (3, 2), (3, 2)], [(6, 3), (5, 3), (3, 3), (3, 3)], [(6, 4), (5, 4), (3, 4), (3, 4)]]

期望的输出:

[(6, 0),(5, 1),(3, 2),(3, 3)]

3 个答案:

答案 0 :(得分:2)

尝试enumerate

diff = [(i, j) for j, i in enumerate(r)]

不太优选的方式是使用zip

diff = list(zip(r, range(len(r))))

答案 1 :(得分:1)

您正在寻找enumerate,它为您提供了具有以下索引的元素:

>>> r = [6, 5, 3, 3]
>>> output = [(val, indx) for indx, val in enumerate(r)]
>>> output
[(6, 0), (5, 1), (3, 2), (3, 3)]

理解枚举的简单方法:

diff = [(r[i], i) for i in range(len(r))]

答案 2 :(得分:1)

我认为你要求enumerate()提供的功能(获取可迭代的值和索引)

r = [6, 5, 3, 3]
print([(val, i) for i, val in enumerate(r)])