Home > OS >  How to sort values from a list based on the list contents?
How to sort values from a list based on the list contents?

Time:12-18

I have a nested list of data and I want to extract and sort different values into relevant new lists.

Is there a way to to say "If the list contains a certain element, put the nth element from the list into a new list"?

For example, I have this list of lists:

data = [
        ['1', 'google', '40', '100'],
        ['2', 'ebay', '70', '60'],
        ['3', 'amazon', '20', '120']
       ]

e.g. I want to say "if a list contains 'google' put the 4th value in the list into a new google list", the same with 'ebay' and 'amazon'.

I've tried:

for list in data:
   if 'google' in list:
      google.append(list[3])

...but this just leaves me with an empty list. What have I missed?

CodePudding user response:

for list in data:
   if 'google' in list:
      google.append(list[3])

list is a predefined keyword, use some other word as a variable. In your case creating a new list with variable name as your data is very complex stuff. Try to put value inside the dict.

CodePudding user response:

Sounds like you actually want a dictionary. You should almost never want or need a set of variables whose name indicates that a search produced a match; instead, create a single variable with a structure, like

{ 'google': ['100'],
  'ebay': ['60'],
  'amazon': ['120']}

Here is a simple snippet to do that:

from collections import defaultdict

collected = defaultdict(list)
for item in lst:
    if item[1] in {'google', 'amazon', 'ebay'}:
        collected[item[2]].append(item[3])

Your list obviously cannot be called list so I renamed it to lst. The use of defaultdict simplifies the handling of the dict in that you don't have to make sure that a key is already present in the dict before you can append to its value.

If you want to process all items, not just the three you have enumerated, just take out the if condition and process all entries in the loop unconditionally.

CodePudding user response:

I think you just have a problem with the for iteration, look at what i've tried:

list = [['1', 'google', '40', '100'],
['2', 'ebay', '70', '60'],
['3', 'amazon', '20', '120']]

google = []

for l in list:
    if 'google' in l:
        google.append(l[3])

print(google)

The problem you are having is that you refence 'list' instead of a corect operator. This prints ['100'] (might want to convert it to int before appending with google.append(int(l[3]))).

  • Related