[英]How to sort a list to be in descending order by numbers after :
I need to be able to order the values in a descending order. 我需要能够以降序排列值。 this is the output i have and it is in a list form,
这是我的输出,它是列表形式,
Eutherian - Bat - Microbat : 28
Avian - Other : 203
Marsupial - Macropod : 14
Eutherian - Bat - Flying Fox : 25
Reptile - Lizard : 28
Avian - Waterbird : 19
Marsupial - Koala : 13
Marsupial - Possum/Glider : 50
Reptile - Snake - Terrestrial : 18
Amphibian - Native Frog : 2
Reptile - Turtle - Freshwater : 3
Marsupial - Dasyurid : 4
Marsupial - Bandicoot : 4
Avian - Seabird/Pelican : 5
Avian - Raptor : 3
Reptile - Snake - Marine : 1
Reptile - Turtle - Marine : 2
i have tried using the split function but i cant get it to work and i have tried using tuples? 我试过使用split函数,但我无法使其正常工作,并且试过使用元组? i am a complete beginner
我是一个完整的初学者
the result i am trying to achieve is to have the most reports to the worst to then make a pie chart showing this 我想要达到的结果是,将最坏的报告最多,然后制作一个饼图显示
You can use the key
option in the sort function. 您可以在排序功能中使用
key
选项。
A small lambda can help you separate the number from the string. 较小的lambda可以帮助您将数字与字符串分开。
For example 例如
x = ['A: 10', 'B: 2', 'C: 12']
x.sort(key=lambda y:int(y.split(":")[-1]), reverse=True)
print(x)
Which results in: 结果是:
['C: 12', 'A: 10', 'B: 2']
If you have 1 big string you want to split into a list of lines, then split each line into a tuple like ("Eutherian - Bat - Microbat", 28)
with 2nd item as integer and then sort by the integer value descending: 如果您有1个大字符串,则希望拆分成几行,然后将每行拆分成一个元组,例如
("Eutherian - Bat - Microbat", 28)
其中第二项为整数,然后按整数值降序排序:
lines = """
Eutherian - Bat - Microbat : 28
Avian - Other : 203
Marsupial - Macropod : 14
""".strip().split('\n')
tuples = []
for l in lines:
k, v = l.split(' : ')
tuples.append((k, int(v)))
sorted_tuples = sorted(tuples, key=lambda item: item[1], reverse=True)
for k, v in sorted_tuples:
print(k, ":", v)
Output: 输出:
Avian - Other : 203
Eutherian - Bat - Microbat : 28
Marsupial - Macropod : 14
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.