Skip to main content
 首页 » 编程设计

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

2025年05月04日24虾米哥

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)