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
180 views
in Technique[技术] by (71.8m points)

python - Retrieving values of sublists within a list

so I have a list which I retrieved from converting a data frame to a list that looks like the following (it goes on for many countries):

list = [[NL, Q1, 1400], [NL, Q2, 1800], [NL, Q3, 1900], [NL, Q4, 2000], [FRA, Q1, 2400],[FRA, Q1, 2600], ...]

Now, I need to to retrieve the third values for each country and append them to their own list, so the output should be:

NL = [1400, 1800, 2000]
FRA = [2400, 2600, ...]

How can I achieve this? I tried to use a for loop statement, but then I only get the sublists.

question from:https://stackoverflow.com/questions/66051830/retrieving-values-of-sublists-within-a-list

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

1 Answer

0 votes
by (71.8m points)

I would construct a dictionary, where for each key it contains a list of values of that key in the original list.

from collections import defaultdict

values_per_country = defaultdict(list)
for country, _, value in li:
    values_per_country[country].append(value)

Then you can get all the values for, say, NL, as values_per_country["NL"] and optionally assign it to a variable if you wish.


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

...