我想为每个项目和事件的排名(1-5)创建一个计数器。
例如,结构是[" DATE"," PRODUCT"," RANKING"]
[["1/1/15", "Product 1", "4"], ["1/1/15", "Product 1", "4"],
["2/2/15", "Product 1", "1"], ["1/1/15", "Product 2", "1"],
["1/1/15", "Product 2", "1"], ["3/1/15", "Product 2", "1"]]
想要的输出是
Date: 1/1/15, Product: 1, Ranking: 4, Seen: 2
Date: 2/2/15, Product: 1, Ranking: 1, Seen: 1
Date: 1/1/15, Product: 2, Ranking: 1, Seen: 2
Date: 3/1/15, Product: 2, Ranking: 1, Seen: 1
我想制作每个日期的计数器,每个产品与排名分开。
cc = Counter((rank, week) for rank, week in date_array)
我已经尝试过,但这只能作为日期的计数器,但我想采用不同的产品。
我该怎么做?它会是嵌套计数器吗?最后,我想将此信息写入CSV。
答案 0 :(得分:3)
与之前提供的模式相同,将嵌套列表转换为元组,这里是通用表单,无需解压缩:
c = Counter(tuple(i) for i in data)
for k, v in c.items():
print("Date: {}, Product: {}, Ranking: {}, Seen: {}".format(*k, v))
答案 1 :(得分:0)
从您给定的输出中,它看起来就像您要尝试获取一个计算整个元组的Counter
对象。这简直太容易了。
from collections import Counter
data = [["1/1/15", "Product 1", "4"], ["1/1/15", "Product 1", "4"],
["2/2/15", "Product 1", "1"], ["1/1/15", "Product 2", "1"],
["1/1/15", "Product 2", "1"], ["3/1/15", "Product 2", "1"]]
cc = Counter(map(tuple, data))
for grp,seen in cc.items():
date, product, ranking = grp
product = product.split()[-1] # grab just the product number
# consider changing this in your data model
ordering = [date, product, ranking, seen]
print("Date: {}, Product: {}, Ranking: {}, Seen: {}".format(*ordering))