使用map和filter/reduce来计算一个序列中事物出现的次数(python)

发布于 2024-12-29 21:46:16 字数 388 浏览 1 评论 0原文

我需要列出 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

但我需要这样做,所以我使用地图和过滤器或减少..我不知道如何做到这一点?

I need to make a list of 50 random colours, then count how many times each colour has come up in that sequence. the only way i have found to do this is as shown below:

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

but i need to do it so i use map and filter or reduce.. i can't work out how to do it this way ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倾城月光淡如水﹏ 2025-01-05 21:46:16
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
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
梦里人 2025-01-05 21:46:16

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

You can use random.choice() to populate your random_colors list:

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

And then one way to count all the occurances using map() and filter() can be:

c = dict(map(lambda to_filter: (to_filter, len(filter(lambda x: to_filter == x, random_colors))), colors))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文