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

标签 python list python-2.7 multidimensional-array

给定数据

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/

相关文章:

python - 我可以将一个字符串拆分成一个嵌套列表,其中外部列表​​包含每个句子的列表,内部列表包含每个句子的单词吗?

python - 创建特定模式的两个列表的快速方法

python - 回文函数在 Python 中不起作用

python - Python-3 中的 Long 类型,NameError : name 'long' is not defined

python - 使用 Bokeh 禁用轴上的科学记数法

python - Twisted/tkinter 程序在退出时崩溃

python - 在 python 中读取列表

python - StringIO 中的就地替换

python - 什么是适合 Python 的结构模块的缓冲区

python - 从给定的项目列表创建子列表