简体   繁体   中英

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.

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.

You can use itertools.groupby Just need make sure the data is sorted which yours seems to be:

from itertools import groupby
from operator import itemgetter

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

output = {k: [l[2] for l in g] for k, g in groupby(data, itemgetter(0))}

{'NL': [1400, 1800, 1900, 2000], 'FRA': [2400, 2600]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM