gpt4 book ai didi

python - for循环将相同的值加在一起并制作JSON格式

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:57 27 4
gpt4 key购买 nike

test=[]
sites = sel.css(".info")
for site in sites:
money = site.xpath("./h2[@class='money']/text()").extract()
people = site.xpath("//p[@class='poeple']/text()").extract()
test.append('{"money":'+str(money[0])+',"people":'+str(people[0])+'}')

我的结果 test 是:

['{"money":1,"people":23}', 
'{"money":3,"people":21}',
'{"money":12,"people":82}',
'{"money":1,"people":54}' ]

我被两件事困住了:

一个是我打印的test类型是字符串,所以不像JSON格式

二是 money 值与 1 是重复的,所以我需要把人加在一起,
所以我想要的最终格式是:

[
{"money":1,"people":77},
{"money":3,"people":21},
{"money":12,"people":82},
]

我该怎么做?

最佳答案

我会在 dict 中收集钱条目并将人员加起来作为值,输出到 json 确实应该使用 json 库完成(我没有测试代码但它应该让你知道你如何可以解决问题):

money_map = {}
sites = sel.css(".info")
for site in sites:
money = site.xpath("./h2[@class='money']/text()").extract()[0]
people = int(site.xpath("//p[@class='poeple']/text()").extract()[0])
if money not in money_map:
money_map[money] = 0

money_map[money] += people

import json
output = [{'money': key, 'people': value} for key, value in money_map.items()]
json_output = json.dumps(output)

关于python - for循环将相同的值加在一起并制作JSON格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32633195/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com