Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...