python - 获取嵌套列表中特定索引的不同值

标签 python nested-lists

我有一个包含大约 100 万条记录的嵌套列表,例如:

l = [['a', 'b', 'c', ...], ['d', 'b', 'e', ...], ['f', 'z', 'g', ...],...]

我想获取第二个索引上内部列表的不同值,以便我的结果列表如下:

resultant = ['b', 'z', ...]

我尝试过嵌套循环,但速度不快,任何帮助将不胜感激!

最佳答案

由于您想要唯一的项目,您可以使用 collections.OrderedDict.fromkeys() 来保持顺序和唯一的项目(因为使用哈希表作为键)并使用 zip( ) 获取第二个项目。

from collections import OrderedDict

list(OrderedDict.fromkeys(zip(my_lists)[2]))

在 python 3.x 中,由于 zip() 返回一个迭代器,您可以执行以下操作:

colls = zip(my_lists)
next(colls)
list(OrderedDict.fromkeys(next(colls)))

或者在dict.formkeys()中使用生成器表达式:

list(OrderedDict.fromkeys(i[1] for i in my_lists))

演示:

>>> lst = [['a', 'b', 'c'], ['d', 'b', 'e'], ['f', 'z', 'g']]
>>> 
>>> list(OrderedDict().fromkeys(sub[1] for sub in lst))
['b', 'z']

关于python - 获取嵌套列表中特定索引的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143204/

相关文章:

python - 要本地化的字符串中间的参数

python - 我应该播种随机数生成器吗?

python - PyBrain 训练多输出模块

r - 如何更有效地将嵌套列表展平为一个列表而不是使用 unlist 方法?

jquery - 如何在jquery中对嵌套的li进行编号

python - 虾属性错误 : 'NoneType' object has no attribute 'get_comments'

python - TensorFlow Iris load_csv_with_header( )

python - 为什么在这个列表推导中需要这个列表切片?

python - 我有一个列表列表,我想按 10 分组

java - 比较父列表结构中的嵌套列表以获取java中特定索引中的值