如何从现有列表列表中创建第一个元素的新列表 [英] How to make a new list of first elements from existing list of lists
问题描述
我在下面有一个列表.我需要使用它来创建仅包含国家/地区名称的新列表.如何循环 x
以获得国家名称列表?
I have a list below. I need to use it to create a new list with only country names.
How do I loop x
in order to have a list of country names?
x = [["UK", "LONDON", "EUROPE"],
["US", "WASHINGTON", "AMERICA"],
["EG", "CAIRO", "AFRICA"],
["JP", "TOKYO", "ASIA"]]
结果应该像
UK
US
EG
JP
推荐答案
您有两种方法
使用for循环
countries = []
for e in x:
countries.append(e[0])
或具有列表理解功能,在大多数情况下,这是更好的选择
or with list comprehensions, which would be in most cases the better option
countries = [e[0] for e in x]
此外,如果您的数据源是一个生成器(在这种情况下不是),或者如果您正在对每个元素进行一些昂贵的处理(在这种情况下也不是),则可以使用 generator表达式
,方法是更改方括号()
Furthermore, if your data source is a generator (which it isn't in this case), or if you're doing some expensive processing on each element (not this case either), you could use a generator expression
by changing the square brackets []
for parenthesis ()
countries = (e[0] for e in x)
这将按需计算元素,并且如果数据源太长或与列表理解相比,生成器也将减少内存占用.
This will compute on demand the elements, and if the data source is too long or a generator will also reduce the memory footprint compared to a list comprehension.
这篇关于如何从现有列表列表中创建第一个元素的新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!