python列表-存储最流行的颜色
好吧,我想知道最流行的颜色是什么,我能用列表吗python列表-存储最流行的颜色,python,list,Python,List,好吧,我想知道最流行的颜色是什么,我能用列表吗 popular.append("red") popular.append("blue") popular.append("green") popular.append("red") popular.append("yellow") popular.append("red") popular.append("blue") popular.append("red") popular.append("yellow") 我想要的是 red,blue,ye
popular.append("red")
popular.append("blue")
popular.append("green")
popular.append("red")
popular.append("yellow")
popular.append("red")
popular.append("blue")
popular.append("red")
popular.append("yellow")
我想要的是
red,blue,yellow,green
有没有一种简洁的方法可以用Python列表来实现这一点?我确实记得我在网上看到过一篇关于这个列表的帖子,以及它可以用来做的所有很酷的事情。我记得这就是其中之一
假设我想存储一个用户在我的网站上访问过的最热门的页面-比如前5个访问量最大的页面-我可以用列表或字典来实现吗-这是一种合理的方法吗?您可以使用该类来获取列表中出现次数的信息
如果您正在自己构建列表,而不是已经拥有包含数据的列表,您可以使用字典并以每种颜色为键递增值
基于您的编辑的更多详细信息:
您选择的方法取决于数据模型的外观
如果您的站点统计信息由某个第三方模块处理,那么它可能只提供一个api,返回给定用户的站点访问列表。因为起始点是一个列表,所以将其输入到计数器
,然后从那里提取最上面的值是有意义的
但是,如果您自己保存此数据的持久性存储,则直接将值输入字典(page是键,visit count是值)是有意义的。通过这种方式,您可以快速访问每页的访问次数,并通过在键值对上进行一次迭代,找到前五名中的页面。列表。计数(x)
将为您提供x出现在列表中的次数:
从这一点出发,订购物品非常容易。让我们从以下内容开始:
@斯皮迪:当你提到“趋势”时,我想你的意思是你想看看最后1000种(大约1000种)颜色,看看哪一种是最常见的
您可以使用(类似于列表)保存最后的项目,并更新计数器进行计数:
from collections import Counter, deque
def trending(seq, window=1000, n=5):
""" For every item in `seq`, this yields the `n` most common elements.
Only the last `window` elements are stored and counted """
c = Counter()
q = deque()
it = iter(seq)
# first iterate `window` times:
for _ in xrange(window):
item = next(it) # get a item
c[item]+=1 # count it
q.append(item) # store it
yield c.most_common(n) # give the current counter
# for all the other items:
for item in it:
drop = q.popleft() # remove the oldest item from the store
c[drop] -=1
if c[drop]==0:
# remove it from the counter to save space
del c[drop]
# count, store, yield as above
c[item] +=1
q.append(item)
yield c.most_common(n)
for trend in trending(popular, 5, 3):
print trend
如果您使用的是python<2.7,但它没有,那么您可以执行以下操作:
>>> popular = ['red', 'green', 'blue', 'red', 'red', 'blue']
>>> sorted(set(popular), key=lambda color: popular.count(color), reverse=True)
['red', 'blue', 'green']
为什么它必须是一个列表?这是一个错误的工具…我见过各种各样的解决方案,它们会存储所有的选择-似乎记得是一个解决方案,列表中没有存储所有的选择-只是最流行的,或者趋势?所以可以说商店里有10种流行的颜色。但正如我所说,我可能在红牛上做梦。没有理由,如果你看到我上面的评论-这不是存储所有选择的情况-所以可能是趋势?这就是为什么我问,当你计算项目时,你想要一本只存储计数器的字典,不是一个存储所有元素的列表。抱歉,如果我用错误的方法处理这个问题,我刚刚添加了一些关于我正在尝试做什么的详细信息-我愿意使用最好的方法-我想我记得我曾经看到过一篇关于使用列表作为堆栈、队列和存储用户最流行的选择的帖子,这把我推向了错误的方向。这真的很聪明-我想这就是我想要的,我将使用该代码,看看我是否可以将其配置并使其工作-可能需要一些帮助-
>>> popular = ['red', 'green', 'blue', 'red', 'red', 'blue']
>>> sorted(set(popular), key=lambda color: popular.count(color), reverse=True)
['red', 'blue', 'green']