使用map和filter/reduce统计序列中元素出现次数(python)

1 投票
2 回答
1513 浏览
提问于 2025-04-17 11:59

我需要生成一个包含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来实现这个功能……我不知道该怎么做。

2 个回答

0

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

撰写回答