【问题标题】:Using map and filter/reduce to count how many times things come up in a sequence (python)使用 map 和 filter/reduce 计算序列中出现的次数(python)
【发布时间】:2012-02-22 15:08:20
【问题描述】:

我需要列出 50 种随机颜色,然后计算每种颜色在该序列中出现的次数。我发现这样做的唯一方法如下所示:

colours = [ "Red", "Blue", "Green", "Yellow", "Purple", "Orange", "White", "Black" ]
numbers = map(lambda x : random.randint(0,7), range(50))
randomcolours = map(lambda i: colours[i], numbers)
print randomcolours
x=collections.Counter(randomcolours)
print x

但我需要这样做,所以我使用 map 和 filter 或 reduce.. 我不知道该怎么做?

【问题讨论】:

  • 所以你问如何使用reduce() 实现collections.Counter?那是你的问题吗? reduce 文档的哪一部分令人困惑?您能否提供具体的报价或参考资料?

标签: python map filter count reduce


【解决方案1】:
random_colors = [random.choice(colors) for x in range(50)]

#because python's lambda is crappy, an extra local/global function must be defined
def count_color(di, color):
    di.setdefault(color, 0)
    di[color] = di[color]+1
    return di

result = reduce(count_color, random_colors, {})
#The result is what you want

【讨论】:

    【解决方案2】:

    您可以使用random.choice() 来填充您的random_colors 列表:

    random_colors = [random.choice(colors) for x in range(50)]
    

    然后使用map() 和filter() 计算所有出现次数的一种方法是:

    c = dict(map(lambda to_filter: (to_filter, len(filter(lambda x: to_filter == x, random_colors))), colors))
    

    【讨论】:

      猜你喜欢
      • 2013-01-22
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2016-08-01
      • 2019-04-04
      • 2019-01-10
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多