我想从列表中消除重复的元素,并返回重复的时间元素的数量
尽管我使用的是列表,但在json格式中,计数器抛出错误
如果不能在这里使用dict inside list,请告诉我任何快速的替代方案(因为len(all_response)将是6位数)
下面是我的代码:
from collections import Counter
all_response = [
{
"stock_id": 315,
"product_id": 315
},
{
"stock_id": 315,
"product_id": 315
},
{
"stock_id": 1,
"product_id": 1
},
{
"stock_id": 2,
"product_id": 2
},
{
"stock_id": 2,
"product_id": 2
},
{
"stock_id": 6,
"product_id": 6
}]
stock_ids = []
d = Counter(all_response)
for i in all_response:
if i['stock_id'] not in stock_ids:
stock_ids.append({'stock_id':i['stock_id']})
stock_ids.append({'product_count': d[i['stock_id']]})
print(stock_ids)
预期输出:
[
{
"stock_id": 315,
"product_count": 2
},{
"stock_id": 1,
"product_count": 1
},
{
"stock_id": 2,
"product_count": 2
},
{
"stock_id": 6,
"product_count": 1
}]
发布于 2021-08-02 09:24:46
original_list = [{'stock_id': 315, 'product_id': 315}, {'stock_id': 1, 'product_id': 1}, {'stock_id': 2, 'product_id': 2}, {'stock_id': 2, 'product_id': 2}, {'stock_id': 6, 'product_id': 6}]
intermediate_result = {}
for i in original_list:
if i["stock_id"] in intermediate_result.keys():
intermediate_result[i["stock_id"]] = intermediate_result[i["stock_id"]]+1
else:
intermediate_result[i["stock_id"]] = 1
result = []
for k,v in intermediate_result.items():
result.append({"stock_id": k, "count": v})
print(result)
[{'stock_id': 315, 'count': 1}, {'stock_id': 1, 'count': 1}, {'stock_id': 2, 'count': 2}, {'stock_id': 6, 'count': 1}]
关于你的代码:
stock_ids = []
d = Counter(all_response)
for i in all_response:
# here is not okay. stock_ids is list of dictionaries
# so you comparing integer id with one of dictionaries
if i['stock_id'] not in stock_ids:
# here is half okay (you appending only id key, without count key)
stock_ids.append({'stock_id':i['stock_id']})
# here is not okay, because you trying to append new element to list
# you should append only once if you want only one dictionary element
stock_ids.append({'product_count': d[i['stock_id']]})
发布于 2021-08-02 09:30:34
正如错误消息所说,Counter
不能接受dict
作为输入。但是您可以从您感兴趣的键创建一个项目列表。
d = Counter(x['stock_id'] for x in all_response)
stock_ids = [{'product_id': x, 'product_count': d[x]} for x in d]
https://stackoverflow.com/questions/68618955
复制相似问题