12

私が今持っているコード:

from collections import Counter
c=Counter(list_of_values)

戻り値:

Counter({'5': 5, '2': 4, '1': 2, '3': 2})

このリストを、出現回数ではなく、項目ごとに数値(/アルファベット)順に並べ替えたいと思います。これを次のようなペアのリストに変換するにはどうすればよいですか。

[['5',5],['2',4],['1',2],['3',2]]

注:c.items()を使用すると、次のようになります:dict_items([( '1'、2)、( '3'、2)、( '2'、4)、( '5'、5)])それは私を助けません...

前もって感謝します!

4

5 に答える 5

19

エラー...

>>> list(collections.Counter(('5', '5', '4', '5')).items())
[('5', 3), ('4', 1)]
于 2012-06-15T18:02:57.947 に答える
1

あなたはただ使うことができますsorted()

>>> c
Counter({'5': 5, '2': 4, '1': 2, '3': 2})
>>> sorted(c.iteritems())
[('1', 2), ('2', 4), ('3', 2), ('5', 5)]
于 2012-06-15T18:42:47.983 に答える
1

アイテムの番号順/アルファベット順で並べ替える場合:

l = []
for key in sorted(c.iterkeys()):
    l.append([key, c[key]])
于 2012-06-15T18:38:27.000 に答える
0

カウンターを辞書に変換し、次のように 2 つの個別のリストにスピルします。

c=dict(c)
key=list(c.keys())
value=list(c.values())
于 2019-07-10T10:30:22.260 に答える
-3
>>>RandList = np.random.randint(0, 10, (25))
>>>print Counter(RandList)

のようなものを出力します...

Counter({1: 5, 2: 4, 6: 4, 7: 3, 0: 2, 3: 2, 4: 2, 5: 2, 9: 1})

そしてこれで…

>>>thislist = Counter(RandList)
>>>thislist = thislist.most_common()
>>>print thislist
[(1, 5), (2, 4), (6, 4), (7, 3), (0, 2), (3, 2), (4, 2), (5, 2), (9, 1)]
>>>print thislist[0][0], thislist[0][1]
1 5
于 2016-05-27T22:10:10.327 に答える