【发布时间】:2021-04-14 21:00:48
【问题描述】:
假设我有一个 Python 列表,其中每个元素代表一天以及商店中有多少产品:
l = [
[a, a, a, b, c],
[a, a, b, b, c],
[a, b, b, c, c]
]
我想创建一个摘要,显示:
Day 1: a:3, b:1, c:1
Day 2: a:2, b:2, c:1
Day 3: a:1, b:2, c:2
我需要一种格式,以便我可以绘制一段时间内的产品可用性图表。
我试过这个:
from collections import Counter
Counter(x for sublist in l for x in sublist)
但这会将所有列表中的元素向上计数,而不是返回每个子列表的结果。
谢谢大家,这是包括图表在内的最终解决方案:
from collections import Counter
d = {i:Counter(sublist) for i, sublist in enumerate(l, start=1)}
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df = df.melt('index', var_name='product', value_name='vals')
df['product'] = df['product'].map({'A': 'a', 'B': 'b','C': 'c','D': 'd'})
sns.lineplot(x="index", y="vals", hue='product', data=df)
【问题讨论】:
-
试试这个
[Counter(sublist) for sublist in l]
标签: python list dictionary counter