如何通过给定索引从嵌套列表中提取元素 [英] How to extract elements from nested lists by given index
本文介绍了如何通过给定索引从嵌套列表中提取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的列表列表:
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屋!
查看全文