Python questions [('a', 5), ('b', 2), ('c', 1), ('b', 2), ('a', 9), ('d', 3), ('c', 13), ('e', 6)] sort data in numbers like this.

Asked 2 years ago, Updated 2 years ago, 62 views

data = [('a', 5), ('b', 2), ('c', 1), ('b', 2), ('a', 9), ('d', 3), ('c', 13), ('e', 6)] This kind of data [('a', 14), ('c', 14), ('e', 6), ('b', 4), ('d', 3)] I'd like to make a list that sorts the values in descending order, where the first value of a tuple is a letter, and the last value is a string. What should I do?

list tuple python

2022-09-20 19:38

1 Answers

>>> data = [('a', 5), ('b', 2), ('c', 1), ('b', 2), ('a', 9), ('d', 3), ('c', 13), ('e', 6)]
>>> sum_dict = {}
>>> for ch, num in data:
    sum_dict[ch] = sum_dict.get(ch, 0) + num


>>> sum_dict
{'a': 14, 'b': 4, 'c': 14, 'd': 3, 'e': 6}
>>> sorted(sum_dict.items(), key=lambda e: e[1])
[('d', 3), ('b', 4), ('e', 6), ('a', 14), ('c', 14)]
>>> sorted(sum_dict.items(), key=lambda e: e[1], reverse=True)
[('a', 14), ('c', 14), ('e', 6), ('b', 4), ('d', 3)]


2022-09-20 19:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.