Python:给定一个列表列表,创建一个按内部列表中出现次数排序的列表

时间:2013-06-09 23:54:19

标签: python list

我有一份清单清单:

[['a','b','c'], ['a'], ['a','b']]

我想对它进行排序并返回一个列表,因此输出如下所示:

['a', 'b', 'c']

即。按每个元素出现的次数排序。 a出现3次,b出现两次,c出现一次。

我该怎么做?

6 个答案:

答案 0 :(得分:7)

使用collections.Counteritertools.chain.from_iterablelist comprehension

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,这确实很有帮助。

答案 1 :(得分:5)

使用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']

答案 2 :(得分:4)

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..位只是一个扁平化的习语。你可以用

>>> 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')

答案 3 :(得分:2)

这有效:

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']

答案 4 :(得分:1)

您可以使用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']

答案 5 :(得分:0)

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