【问题标题】:Count occurrence of tuples with Python使用 Python 计算元组的出现次数
【发布时间】:2015-11-17 05:07:43
【问题描述】:

我正在尝试将显示产品和成本的 Python 元组列表转换为以给定成本显示成本和产品数量的元组列表。

例如,给定以下输入:

[('Product1', 9), ('Product2', 1),
 ('Product3', 1), ('Product4', 2),
 ('Product5', 3), ('Product6', 4),
 ('Product7', 5), ('Product8', 6), 
 ('Product9', 7), ('Product10', 8), 
 ('Product11', 3), ('Product12', 1), 
 ('Product13', 2), ('Product14', 3), 
 ('Product15', 4), ('Product16', 5), 
 ('Product17', 6), ('Product18', 7)]

我正在尝试在 Python 中创建一个可以呈现以下内容的函数。即值 1 为三种不同的产品渲染了 3 次,因此为 (1, 3)。

[(1, 3), (2, 1), (3, 2), (4, 1), (5, 2), (6, 2), (7, 2), (8, 1) (9, 1)]

【问题讨论】:

  • 您只需要遍历元组并为每个值创建一个存储桶,将该存储桶中的值增加 1,这并不难。写一些代码伙伴
  • @BrijRajSingh - 这不是“pythonic”的做法。
  • @JasonEstibeiro:Brij 的解决方案 Pythonic:使用普通的dict 很容易,但我同意该技术已被Counter 取代。

标签: python python-2.7 tuples


【解决方案1】:

也许collections.Counter 可以解决你的问题:

>>> from collections import Counter
>>> c = Counter(elem[1] for elem in given_list)

输出将如下所示:

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

如果您希望它在问题中指定的列表中,那么您可以这样做:

>>> list(c.iteritems())
[(1, 3), (2, 2), (3, 3), (4, 2), (5, 2), (6, 2), (7, 2), (8, 1), (9, 1)]

【讨论】:

  • 简单。简单的。高效的。答案很好!
  • 为什么使用列表组合而不是list(c.iteritems())?顺便说一句,你不应该使用 list 作为变量名,因为它会隐藏内置的 list 类型,这可能会导致神秘的错误。
  • @PM2Ring - 感谢您的建议。我试图执行list(c.iteritems()),但出现错误。现在,我意识到这是因为你的第二个建议给我的错误。显然,我发现了神秘的错误。 :P
  • 太棒了,效果很好:) 谢谢大家的帮助!
  • 我很想知道它的复杂性(运行时间/执行时间)。
【解决方案2】:

最快的方法是使用mapitemgetter

from operator import itemgetter

l = [('Product1', 9), ('Product2', 1),
 ('Product3', 1), ('Product4', 2),
 ('Product5', 3), ('Product6', 4),
 ('Product7', 5), ('Product8', 6),
 ('Product9', 7), ('Product10', 8),
 ('Product11', 3), ('Product12', 1),
 ('Product13', 2), ('Product14', 3),
 ('Product15', 4), ('Product16', 5),
 ('Product17', 6), ('Product18', 7)]

cn = Counter(map(itemgetter(1), l))

print(list(cn.items()))

【讨论】:

  • 我很想知道上面每个 4 答案的运行时间。请分享:)
  • @SaifulIslam,所有 dict 方法都是 O(n) 最坏情况,使用 list.count 是 O(n^2) 。做一个dict查找是常数时间,用list.count遍历列表是O(n)
  • 那么为什么你的方法是最快的?很抱歉问简单的问题(可能是)。
  • @SaifulIslam, 复杂度是一样的,只是map和itemgetter都是c级做的
【解决方案3】:

另一种方式是Defaultdict-

from collections import defaultdict

dd = defaultdict(int)

d= [('Product1', 9), ('Product2', 1),
 ('Product3', 1), ('Product4', 2),
 ('Product5', 3), ('Product6', 4),
 ('Product7', 5), ('Product8', 6), 
 ('Product9', 7), ('Product10', 8), 
 ('Product11', 3), ('Product12', 1), 
 ('Product13', 2), ('Product14', 3), 
 ('Product15', 4), ('Product16', 5), 
 ('Product17', 6), ('Product18', 7)]
for i in d:
    dd[i[1]]+=1
counts  =  [i for i in dd.iteritems()]
print counts

打印-

[(1, 3), (2, 2), (3, 3), (4, 2), (5, 2), (6, 2), (7, 2), (8, 1), (9, 1)]

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 1970-01-01
    • 2022-11-30
    • 2023-03-12
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    相关资源
    最近更新 更多