-1

Hi there Stackoverflowers.

Have a question about sorting a list of lists first by a given value and then after how many times a given value is presented:

As an example I have the following list which contains the following posts [name,year,color]:
[ [fido,2012,brown],[fluffy,2018,pink],[fido,2016,yellow],[fluffy,2017,orange],[fluffy,2011,red],[minai,2018,blue]]

then I sort the list with sorted like this: list = sorted(list, key=itemgetter(1))

That gives me the list sorted after name so "fido" comes first,"fluffy" second and "minai" last but "fluffy" has occured three times, "fido" two and "minai" one time.

How can I sort the list so fluffy comes first since it appeared three times then fido with two times and lastly minai since it occured only once.

-Regards-

werner
  • 1
  • 4
  • You need to supply your desired sorting criterion as a key function. Work through a tutorial on `sort`. – Prune Oct 15 '20 at 17:28
  • Use a custom key for your sort function based on the counts of the dog names: `name_to_counts = Counter(name for name, birth_year, color in dog_info) # Counter({'fluffy': 3, 'fido': 2, 'minai': 1})` `sorted_dog_info = sorted(dog_info, key=lambda x: (-name_to_counts[x[0]], x))` `print(sorted_dog_info)` **Output:** `[['fluffy', 2011, 'red'], ['fluffy', 2017, 'orange'], ['fluffy', 2018, 'pink'], ['fido', 2012, 'brown'], ['fido', 2016, 'yellow'], ['minai', 2018, 'blue']]` – Sash Sinha Oct 15 '20 at 17:33
  • thanks for your help Prune and Shash Sinha – werner Oct 15 '20 at 17:43

1 Answers1

1

You can set up a custom sorting key that first checks for the string comparison, then the number of occurances (Counter helps for this):

from collections import Counter

vals = [
    ["fido", 2012, "brown"],
    ["fluffy", 2018, "pink"],
    ["fido", 2016, "yellow"],
    ["fluffy", 2017, "orange"],
    ["fluffy", 2011, "red"],
    ["minai", 2018, "blue"],
]

cnts = Counter(v[0] for v in vals)
sorted_vals = list(sorted(vals, key=lambda v : (v[1], -cnts[v[0]])))

Output:

[['fluffy', 2011, 'red'],
 ['fido', 2012, 'brown'],
 ['fido', 2016, 'yellow'],
 ['fluffy', 2017, 'orange'],
 ['fluffy', 2018, 'pink'],
 ['minai', 2018, 'blue']]
Cihan
  • 2,267
  • 8
  • 19