1

There is a question here sort list by frequency

I don't want to bother the collections library. Here is my solution using 'key' in the sort

S = ['a', 'a', 'b', 'c', 'c', 'c']
S.sort(reverse=True, key=S.count)

or

S.sort(reverse=True, key=lambda x: S.count(x))

But it doesn't work. Any problem with my key setting? Thanks

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
jason
  • 1,998
  • 3
  • 22
  • 42
  • Weird. That should (in theory) be the same as `S = sorted(S, reverse=True, key=S.count)` and that works fine... – Nick Dec 26 '19 at 03:19
  • What you are trying to do is mutating the array while iterating over it (which is what `S.count()` is implicitly doing). This is sometimes problematic. As @Nick observed, you don't have the same problem when building up a new, sorted, array with essentially the same logic. – John Coleman Dec 26 '19 at 03:34
  • @JohnColeman can you explain more and summary them as `Solution`? Thanks. – jason Dec 26 '19 at 03:43
  • @jason I don't really understand exactly what is happening here, but based on what Nick has observed, it has to be that sort of issue. – John Coleman Dec 26 '19 at 03:47
  • @JohnColeman that's probably it, but the return values from `count` *ought* to be the same no matter how the array has been mutated in the meantime... – Nick Dec 26 '19 at 04:03
  • @JohnColeman Thanks for the link, I try it and something weird behavior happend in my follow-up question. Any though? – jason Dec 26 '19 at 16:15
  • If you have a follow-up question, then please post a new question. – Mark Rotteveel Dec 28 '19 at 12:34

0 Answers0