使用map和filter/reduce来计算一个序列中事物出现的次数(python)
我需要列出 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
random.choice()
填充您的random_colors
列表:然后使用
map()
和filter()
计算所有出现次数的一种方法可以是:You can use
random.choice()
to populate yourrandom_colors
list:And then one way to count all the occurances using
map()
andfilter()
can be: