从嵌套列表中提取元素的最佳方法 [英] Best way to extract elements from nested lists

查看:421
本文介绍了从嵌套列表中提取元素的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表列表:

I have a list of lists which look like this:

[[[12, 15, 0], [13, 15, 25], [14, 15, 25], [16, 16, 66], [18, 15, 55]]]

提取出现在索引位置1的所有元素的最佳方法是什么?我知道我可以使用for循环;

What would be the best way to extract all elements occurring at index position 1. I know I can use a for loop like;

for i in list:
    for j in i:
        print j[2]

但是有没有更多的"pythonic"方式(简短的/简单的/较少的代码/有效的方式)呢?

But is there a more "pythonic" (short /easy /less code/ efficient) way to do this?

推荐答案

您可以使用列表理解:

>>> lst = [[[12, 15, 0], [13, 15, 25], [14, 15, 25], [16, 16, 66], [18, 15, 55]]]
>>> [x[1] for x in lst[0]]
[15, 15, 15, 16, 15]
>>>

以上等同于:

lst = [[[12, 15, 0], [13, 15, 25], [14, 15, 25], [16, 16, 66], [18, 15, 55]]]
final_list = []
for sub_list in lst[0]:
    final_list.append(sub_list[1])

除此之外,它更加简洁,而且避免了对list.append的所有调用(这意味着效率更高).

except that it is a lot more concise and also avoids all those calls to list.append (which means that it is more efficient).

这篇关于从嵌套列表中提取元素的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆