简体   繁体   中英

How to sort may data from largest to smallest using Python

So i have this code, i want to sort out the values of v from largest to smallest.

from itertools import product
from collections import Counter
from random import choice
import itertools
import random
import numpy as np
import numpy.random as random
import pandas as pd
import collections


y = []
for x in [(choice([i for i in range(1,10) if i not in [2]])) for j in range(5)]:
    y.append(x)
a = collections.Counter(y)
for k,v in a.items():
    b = sorted(v)
    print(b)

I tried to used sorted but i got an error like this one: "ypeError: 'int' object is not iterable"

Sort the values like this:

In [1066]: {k: v for k, v in sorted(a.items(), key=lambda item: item[1])}                                                                                                                                   
Out[1066]: {3: 1, 4: 1, 1: 1, 6: 1, 9: 1}

OR if you just want a list of sorted values, you can simply do this:

sorted(a.values())

You can also do this

>>> a = [1, 2, 3]
>>> a.sort(reverse=True)
>>> a
[3, 2, 1]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM