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? 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.
A small lambda can help you separate the number from the string.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.