如何在列表列表中列出元素的有序频率列表

时间:2019-12-01 12:59:57

标签: python list

因此,我想创建一个函数,以这些名称的有序频率给出list作为返回值。基本上所有这些子列表都代表一对朋友,我想将list设为最受欢迎的,而最不受欢迎的人。 我尝试了很多事情,但是这些子列表给我带来了问题。

a = [['Marie', 'Lucas'], ['Lucas', 'Patsy'], ['Emma', 'Lucas'], ['Emma', 'Kevin'], ['Peter', 'Emma'], ['Peter', 'Lucas'], ['Peter', 'Julie'], ['Suzy', 'Tobias']]

3 个答案:

答案 0 :(得分:0)

因此,我们有一个列表列表。我们可以像下面这样遍历它们:

for list in lists:
    for name in list:
        ....

然后,我们可以继续对名称进行计数,并在字典中跟踪频率。

答案 1 :(得分:0)

您可以首先使用两个交叉循环将列表弄平,然后使用collections.Counter来获取最常用名称的排序列表:

from collections import Counter

a = [['Marie', 'Lucas'], ['Lucas', 'Patsy'], ['Emma', 'Lucas'], ['Emma', 'Kevin'], ['Peter', 'Emma'], ['Peter', 'Lucas'], ['Peter', 'Julie'], ['Suzy', 'Tobias']]
flattened = [name for sublist in a for name in sublist]
counter = Counter(flattened)
out = [name for name, count in counter.most_common()]
print(out)
#['Lucas', 'Emma', 'Peter', 'Marie', 'Patsy', 'Kevin', 'Julie', 'Suzy', 'Tobias']

如果您不允许导入任何东西,则可以自己创建计数器,然后按计数对它的元素进行排序:

a = [['Marie', 'Lucas'], ['Lucas', 'Patsy'], ['Emma', 'Lucas'], ['Emma', 'Kevin'], ['Peter', 'Emma'], ['Peter', 'Lucas'], ['Peter', 'Julie'], ['Suzy', 'Tobias']]

# We flatten the list
flattened = [name for sublist in a for name in sublist]
# ['Marie', 'Lucas', 'Lucas', 'Patsy', 'Emma', 'Lucas', ...]

# We count the names in this list
counter = {}
for name in flattened:
    if name not in counter:
        counter[name] = 0
    counter[name] += 1

# dict.items() returns tuples (key, value), we sort by value 
out = [name for name, count in sorted(counter.items(), key=lambda item: item[1], reverse=True)]
print(out)
#['Lucas', 'Emma', 'Peter', 'Marie', 'Patsy', 'Kevin', 'Julie', 'Suzy', 'Tobias']

答案 2 :(得分:0)

使用集合和itertools,我们可以创建一个简单易读的解决方案。

from itertools import chain
from collections import Counter

my_list = [['Marie', 'Lucas'], ['Lucas', 'Patsy'], ['Emma', 'Lucas'], ['Emma', 'Kevin'], ['Peter', 'Emma'], ['Peter', 'Lucas'], ['Peter', 'Julie'], ['Suzy', 'Tobias']]

#we first convert the list of lists to a single list
my_list_flattened = chain.from_iterable(a)

#count the number of occurances
my_list_count = Counter(my_list_flattened)

#finally for the order we can use most_common()
print(my_list_count.most_common())

#[('Lucas', 3), ('Emma', 2), ('Marie', 1), ('Patsy', 1), ('Kevin', 1)]