问题
I have an assignment in which I must create a list of tuples from a string. I do this by splitting the string with .split(). I then iterate over the list and add the items and the number of repetitions of each item into a dict, like so:
for word in s:
if word in count_dict:
count_dict[word] += 1
else:
count_dict[word] = 1
After this I create a list of tuples using:
pairs = count_dict.items()
Followed by:
count_list = []
for pair in pairs:
count_list.append(pair)
count_list.sort(key=lambda x: x[1], reverse=True)
I sort in the order of largest x[1] element in each tuple and reverse the list so that I have the items with he most repetitions up front. My actual assignment is to have the elements with the highest repetitions appear first, and to have elements with the same number of repetitions to appear in alphabetical order behind the largest elements.
回答1:
Another way to reverse a numeric sort is to make the numbers negative in the key function
Now combining with the second sort order into a tuple
count_list.sort(key=lambda x: (-x[1], x[0]))
It's necessary to get rid of the reverse=True
, as otherwise the alphabetical sort will be reversed.
回答2:
count_list.sort(key=lambda x: int(x[1]), reverse=True)
lamba
handles numerical strings in alphabetical order (18 comes before 1503 in reverse
) but handles integers in proper numerical order, so converting x[1]
to an integer does what you're asking for.
来源:https://stackoverflow.com/questions/34009869/sorting-a-list-of-two-element-tuples-numerically-and-alphabetically