Python 列表 - 存储最受欢迎的颜色

2 投票
4 回答
1461 浏览
提问于 2025-04-16 09:31

好吧,假设我想知道最受欢迎的颜色,我能用一个列表来做到这一点吗?

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列表来实现这个?我记得在网上看到过关于列表的帖子,讲了很多它的酷炫用法,我记得这也是其中之一。

假设我想存储用户在我网站上最受欢迎的页面访问记录,比如说访问量前五的页面,我能用列表或者字典来实现吗?这样做合理吗?

4 个回答

2

如果你使用的是 Python 2.7 之前的版本,这个版本没有 collections.Counter 这个功能,你可以这样做:

>>> popular = ['red', 'green', 'blue', 'red', 'red', 'blue']
>>> sorted(set(popular), key=lambda color: popular.count(color), reverse=True)
['red', 'blue', 'green']
4

让我们从正确的方法开始:

popular = ['red', 'blue', 'green', 'red', 'yellow', 
           'red', 'blue', 'red', 'yellow']

from collections import Counter
c = Counter(popular) 
# lists the elements and how often they appear
print c.most_common() 
# -> [('red', 4), ('blue', 2), ('yellow', 2), ('green', 1)]

@spidee:当你提到“流行趋势”时,我猜你的意思是想查看最近的1000种(左右)颜色,看看哪些颜色最常见?

你可以使用dequeue(它就像一个列表)来保存最近的项目,并更新一个计数器来统计它们:

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
4

你可以使用Counter这个类来获取列表中每个元素出现的次数。

如果你是自己创建这个列表,而不是已经有了包含数据的列表,你可以直接用一个字典,每种颜色作为键,出现的次数作为值,每次出现就把对应的值加一。

根据你的修改,更多细节:
你选择的方法取决于你的数据模型是什么样的。

如果你的网站统计数据是由某个第三方模块处理的,它可能只提供一个接口,返回某个用户的访问列表。因为起点是一个列表,所以直接把这个列表传给Counter,然后从中提取出访问最多的几个值是很合理的。

但是,如果你自己在保存这些数据,那么直接把值放进一个字典里(页面作为键,访问次数作为值)会更合适。这样你就可以快速访问每个页面的访问次数,并且只需遍历一次键值对,就能找到访问次数最多的前五个页面。

撰写回答