gpt4 book ai didi

python - 在 python 中为嵌套列表建立索引

转载 作者:行者123 更新时间:2023-12-02 01:35:23 24 4
gpt4 key购买 nike

给定数据

data = [ [0, 1], [2,3] ]

我想索引列表列表中列表中的所有第一个元素。即我需要索引 02

我已经尝试过

print data[:][0]

但它输出完整的第一个列表。即

[0,1]

均匀

print data[0][:]

产生相同的结果。

我的问题具体是如何完成我提到的事情。更一般地说,Python 如何处理双重/嵌套列表?

最佳答案

使用list comprehension :

>>> data = [[0, 1], [2,3]]
>>> [lst[0] for lst in data]
[0, 2]
>>> [first for first, second in data]
[0, 2]

使用map :

>>> map(lambda lst: lst[0], data)
[0, 2]

使用mapoperator.itemgetter :

>>> import operator
>>> map(operator.itemgetter(0), data)
[0, 2]

使用zip :

>>> zip(*data)[0]
(0, 2)

关于python - 在 python 中为嵌套列表建立索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20332601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com