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

标签 python json list

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/

相关文章:

python - 如果行以字母表中的任何字母开头,则打印行

json - WP休息API : How to get number of comments

java.lang.String 无法转换为 JSONObject,其中值已转换为 JSONObject

c# - IQueryable、List、IEnumerator 之间的区别?

python - 类不以多态方式加载

python - 鼠标卡在不同的选择模式pycharm

ios - 如何按位置将json数组保存到数组中?

Python "for in"循环打印列表中的最后一项

python - 为什么 Python +=(加等于)运算符不修改内部函数中的变量?

python - 编写可重用代码