How to make a new list of first elements from existing list of lists

瘦欲@ 提交于 2020-07-27 23:26:55

问题


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"]]

The outcome should look like

UK
US
EG
JP

回答1:


You have two ways

Using a for loop

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]

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 curly ones {}

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.




回答2:


The most readable way is probably:

>>> data = [["UK", "LONDON", "EUROPE"],
            ["US", "WASHINGTON", "AMERICA"],
            ["EG", "CAIRO", "AFRICA"],
            ["JP","TOKYO","ASIA"]]
>>> countries = [country for country, city, continent in data]
>>> countries 
['UK', 'US', 'EG', 'JP']

This list comprehension makes it clear what the three values in each item from data are, and which will be in the output, whereas the index 0 doesn't tell the reader much at all.




回答3:


As cities LONDON, WASHINGTON, CAIRO, TOKYO are present in 1st position(starting from 0) on list items. So get all 1st item from the list items by list compression.

e.g.

>>> x= [["UK", "LONDON", "EUROPE"],["US", "WASHINGTON", "AMERICA"],["EG", "CAIRO", "AFRICA"],["JP","TOKYO","ASIA"]]
>>> [i[1] for i in x]
['LONDON', 'WASHINGTON', 'CAIRO', 'TOKYO']
>>> 

same for countries:

>>> [i[0] for i in x]
['UK', 'US', 'EG', 'JP']



回答4:


If you can find yourself assuming the data x always contains the list in form of [COUNTRY, CITYNAME, CONTINENT], you can retrieve every first items from each list in x like below:

countries = []
for country, cityname, continent in x:
    countries.append(country)

You can shorten above using list comprehension.

>>> countries = [country for country, cityname, continent in x]

Of course you can access the value via an index.

>>> countries = [lst[0] for lst in x]



回答5:


You can also unpack the list and append to new list:

x= [["UK", "LONDON", "EUROPE"],["US", "WASHINGTON", "AMERICA"],["EG", "CAIRO", "AFRICA"],["JP","TOKYO","ASIA"]]

countries = []

for a,b,c in x:
    countries.append(a)


来源:https://stackoverflow.com/questions/28589583/how-to-make-a-new-list-of-first-elements-from-existing-list-of-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!