gpt4 book ai didi

python - 与 defaultdict 结合使用时计数器排序丢失

转载 作者:太空狗 更新时间:2023-10-30 02:24:31 29 4
gpt4 key购买 nike

我正在尝试获取一个由 (item_number, fruit) 元组组成的列表,并计算每种水果在列表中出现的次数。使用 collections.Counter 就足够简单了。我正在使用 most_common()

我遇到的问题是,当尝试同时显示与特定类型水果相对应的 item_numbers 列表时,它们变得乱序了。

这是我的示例代码:

#!/usr/bin/env python

from collections import Counter, defaultdict

mylist = [
(1, 'peach'),
(2, 'apple'),
(3, 'orange'),
(4, 'apple'),
(5, 'banana'),
(6, 'apple'),
(7, 'orange'),
(8, 'peach'),
(9, 'apple'),
(10, 'orange'),
(11, 'plum'),
]

# FIRST, HANDLE JUST COUNTING THE ITEMS

normal_list = []

# append to a simple list
for item_number, fruit in mylist:
normal_list.append(fruit)

# prints just the name of each fruit and how many times it appears
for fruit, count in Counter(normal_list).most_common(10):
print(f'{fruit}\tCount: {count}')

# NOW TRY TO INCLUDE THE LIST IF ITEM NUMBERS ALSO

mydefaultdict = defaultdict(list)

# append to the defaultdict
for item_number, fruit in mylist:
mydefaultdict[fruit].append(item_number)

# prints each fruit, followed by count, and finally the list of IPs for each
for fruit, item_list in Counter(mydefaultdict).most_common(10):
print(f'{fruit}\tCount: {len(item_list)}\tList: {item_list}')

我得到了简单版本的预期输出:

apple   Count: 4
orange Count: 3
peach Count: 2
banana Count: 1
plum Count: 1

但是,当我尝试向其中添加 item_number 列表时,结果不再排序,当我使用小于水果品种总数的 most_common() 值时,这会造成严重破坏:

plum    Count: 1    List: [11]
banana Count: 1 List: [5]
orange Count: 3 List: [3, 7, 10]
apple Count: 4 List: [2, 4, 6, 9]
peach Count: 2 List: [1, 8]

我确定我可以在这里做一些不同的事情,但我不太确定是什么。

最佳答案

Counter(mydefaultdict) 并没有按照您认为 的方式进行操作。您正在将 列表defaultdict 提供给Counter,其目的是计算出现次数,而不是计算长度列出。实际上,Counter 对象的 只是列表,而不是整数。 Counter 不会报错,因为它是 dict 的子类,并且像 dict 一样可以用另一个字典初始化。

要按最长列表 排序,您可以使用 heapq.nlargest使用自定义函数:

from heapq import nlargest

for fruit, item_list in nlargest(10, mydefaultdict.items(), key=lambda x: len(x[1])):
print(f'{fruit}\tCount: {len(item_list)}\tList: {item_list}')

apple Count: 4 List: [2, 4, 6, 9]
orange Count: 3 List: [3, 7, 10]
peach Count: 2 List: [1, 8]
banana Count: 1 List: [5]
plum Count: 1 List: [11]

关于python - 与 defaultdict 结合使用时计数器排序丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52958896/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com