John77 - 1 year ago 98
Python Question

# Python Sort not Working

I have code to sort a list of tuples:

``````s = "betty bought a bit of butter but the butter was bitter"
words = s.split()
l = []
k = []
unique_words = sorted(set(words))
for word in unique_words:
k.append(word)
l.append(words.count(word))

z = zip(k,l)
print z
reversed(sorted(z, key=lambda x: x[1]))
print z
``````

z is the same, list doesn't get sorted or even reversed.

I am trying to sort by the integer value of count.

For an in-place sort, you should use `z.sort()`.

If you insist on using `sorted`, then send the value back to `z`.

So, use either,

``````z.sort(key = lambda x:x[1])
z.reverse()
``````

Or,

``````z = reversed(sorted(z, key=lambda x: x[1]))
``````

Or, a more sophisticated solution could be:

``````z = sorted(z, key=lambda x: x[1], reverse= True)
``````

As a matter of fact, you can get the end result more easily by using `collections.Counter()`

``````from collections import Counter
z = sorted(Counter(s.split()).items(), key = lambda x:x[1], reverse = True)
``````

Sorting by two multiple keys are fine, you can pass them as a tuple. In your case, the solution would be:

``````# first sort by negatives of the second item, then alphabetically.
z = sorted(z, key=lambda x: (-x[1],x[0]))
``````

Output:

``````[('butter', 2), ('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1),
('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download