Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...