在 50 种生成颜色的列表上使用 map 来计数,使用过滤器,并减少或 len,出现的频率

Use map over a list of 50 generated colours to count, using filter, and reduce, or len, the frequency of occurence

Given:

c = ["red", "blue", "green", "yellow", "purple", "orange", "white", "black"]

Generate and print a list of 50 random colours. You will need to use the random module to get random numbers.

Use range and map to generate the required amount of numbers.

Then use map to translate numbers to colours. Then use map over the colours to count (using filter, and reduce or len) how often each colour occurs. Print the result.

这是我目前得到的:

import random
colours = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'white', 'black']
nums = map(lambda x: random.randint(0,7), range(50))
c = map(lambda y: colours[y], nums)

打印时,会从给定列表中提供所需的 50 种随机颜色集。我对从这里搬到哪里感到困惑。

这个也使用 zip,因此您可以参考正在计算的颜色:

zip(colours, map(lambda x: len(filter(lambda y: y==x, c)), colours))

使用 reduce 来计算元素的方法给了我一些想法,我发现这样做的唯一方法是:

map(lambda color: reduce(lambda x,y: x+y, map(lambda y: 1,filter(lambda x: x==color, c))), colours)