I want to sort a 2-D list t = [[3, 3, 3, 'a'], [2, 2, 2, 'b'], [1, 1, 1, 'b']] with each list's last character's frequancy in reverse. since b is 2 times and a is 1 time so sorted list should be t_sorted = [[2,2,2,'b'],[1,1,1,'b], [3,3,3,'a']] I wrote the code:
def mine(a):
return t.count(a[-1])
t = [[3, 3, 3, 'a'], [2, 2, 2, 'b'], [1, 1, 1, 'b']]
print(sorted(t,key = mine, reverse = True))
but it is not working fine. what is the right way to do it without using counter python?
CodePudding user response:
This is because t
doesn't have any 'a's or any 'b's. It has lists which include 'a's and 'b's.
Just check it manually:
>>> t = [[3, 3, 3, 'a'], [2, 2, 2, 'b'], [1, 1, 1, 'b']]
>>> t.count('a')
0
The least confusing way to do it is to just make a (proper) counter of those last elements - let's get only last elements of the sublists and convert it to Counter:
from collections import Counter
t = [[3, 3, 3, 'a'], [2, 2, 2, 'b'], [1, 1, 1, 'b']]
my_count = Counter(elem[-1] for elem in t)
Now we can use our Counter object to be our position:
print(sorted(t,key = lambda x: my_count[x[-1]], reverse = True))
CodePudding user response:
Here's an (inferior) solution that doesn't use Counter:
def mine(a):
return [x[-1] for x in t].count(a[-1])