Martin Bouhier
Martin Bouhier

Reputation: 115

Compare items of a list of list and choose the biggest

lista = [['Apertura','174830','Apertura - Home - Header_n','Variable (950x90)','AR','1','0','0.82','81','1.23',0.3,3],
         ['Apertura','174830','Apertura - Home - Header_n','Variable (950x90)','AR','1','0','0.82','81','1.23',0.25,5]
]

I need to compare all the items on my list. Within each item, we use all items except the last two to compare. if there are items that are the same we choose the item that has the lowest number of the last item that we do not take to compare

>>>['Apertura','174830','Apertura - Home - Header_n','Variable (950x90)','AR','1','0','0.82','81','1.23',0.3,3]

I used this form but know I can't do it with that.

lista = [min(g, key=itemgetter(-2)) for _, g in groupby(lista, key=lambda s: s[:-2])]

Upvotes: 1

Views: 49

Answers (2)

vash_the_stampede
vash_the_stampede

Reputation: 4606

  1 lista = [
  2     [
  3         'Apertura','174830','Apertura - Home - Header_n','Variable (950x90)',
  4         'AR','1','0','0.82','81','1.23',0.3,3
  5     ],   
  6     [
  7         'Apertura','174830','Apertura - Home - Header_n','Variable (950x90)',
  8         'AR','1','0','0.82','81','1.23',0.25,5
  9     ]
 10 ]
 11 
 12 if lista[0][:-2] == lista[1][:-2]:
 13     if lista[0][-1] < lista[1][-1]:
 14         print(lista[0])
 15     else:
 16         print(lista[1])

Output

['Apertura', '174830', 'Apertura - Home - Header_n', 'Variable (950x90)', 'AR', '1', '0', '0.82', '81', '1.23', 0.3, 3]

If I am understanding what you are seeking correctly, could we just do compare the list up to the second to last item, then if equal just compare the last item?

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71620

Why not use sorted with key argument instead of itertools.groupby:

print(sorted(lista,key=lambda x: x[-2]))

OR:

lista.sort(key=lambda x: x[-2])
print(lista)

Upvotes: 0

Related Questions