我有一个列表列表:
[['a','b','c'], ['a'], ['a','b']]
我想对其进行排序并返回一个列表,因此输出如下所示:
['a', 'b', 'c']
即按每个元素出现的次数排序。a 出现 3 次,b 出现两次,c 出现一次。
我该怎么做呢?
使用collections.Counter
,itertools.chain.from_iterable
和列表推导:
from itertools import chain
from collections import Counter
data = [['a', 'b', 'c'], ['a'], ['a', 'b']]
d = Counter(chain.from_iterable(data))
print([i for i, c in d.most_common()])
输出:
['a', 'b', 'c']
注意:当你想计算列表中某些项目的频率时,记得使用Counter
,它真的很有帮助。
用于itertools.chain.from_iterable()
首先展平列表,然后collections.Counter()
对元素进行计数。
>>> from collections import Counter
>>> from itertools import chain
>>> [x[0] for x in Counter(chain.from_iterable(mylist)).most_common())
['a', 'b', 'c']
collections.Counter
应该这样做:
>>> from collections import Counter
>>> lol = [['a','b','c'], ['a'], ['a','b']]
>>> c = Counter(elem for sublist in lol for elem in sublist)
>>> c
Counter({'a': 3, 'b': 2, 'c': 1})
elem for sublist..
bit 只是一个扁平化的习语。你可以使用
>>> Counter(chain.from_iterable(lol))
Counter({'a': 3, 'b': 2, 'c': 1})
相反,在from itertools import chain
. 然后你可以得到最常见的:
>>> c.most_common()
[('a', 3), ('b', 2), ('c', 1)]
然后提取您喜欢的密钥:
>>> [x[0] for x in c.most_common()]
['a', 'b', 'c']
>>> zip(*c.most_common())[0]
('a', 'b', 'c')
这有效:
LoL= [['a','b','c'], ['a'], ['a','b']]
d={}
for e in [i for sub in LoL for i in sub]:
d[e]=d.setdefault(e,0)+1
print sorted(d, key=d.get, reverse=True)
印刷:
['a', 'b', 'c']
您可以使用collections.Counter
为每个子列表中的每个元素保留一个计数器。像这样的东西,
>>> from collections import Counter
>>> lst = [['a','b','c'], ['a'], ['a','b']]
>>> counts = Counter()
>>> for sublst in lst:
... for ele in sublst:
... counts[ele] += 1
...
>>> [ele for ele, _ in counts.most_common()]
['a', 'b', 'c']
from collections import Counter
import operator
mlist= [['a','b','c'], ['a'], ['a','b']]
elist= [x for x,y in sorted(
Counter([l for s in mlist for l in s]).iteritems(),
key=operator.itemgetter(1),reverse=True)]
print elist