猿问

使用 Json 文件过滤单词列表

我的 Json 文件:


{

  "countries": [

  "Australia", "France", "Belgium"

  ]

}

我有一个index_list = ['Germany', 'USA, 'Ireland, Australia, "France", Belgium, "Kenya", "Spain" 我想过滤掉 json 文件中的所有国家/地区。


data_json= json.dumps(data["countries"])

res = filter(lambda i: i not in data_json, index_list)

print(res)

这给了我<filter object at 0x0000022D05C0E6A0>错误。


慕桂英546537
浏览 189回答 3
3回答

月关宝盒

您可以将 JSON 数据转换为 list() 并使用列表理解过滤其他数据。import jsondata_json = list(json.load(open('file.json'))['countries'])index_list = ['Germany', 'USA', 'Ireland', 'Australia', "France", 'Belgium', "Kenya", "Spain"]answer = [country for country in index_list if country not in data_json]print(answer)

30秒到达战场

您可以循环遍历所有元素并检查它们是否存在于 json 列表中,而不是过滤器import jsondata = {"countries": ["Australia", "France", "Belgium"]}index_list = ["Germany", "USA", "Ireland", "Australia", "France", "Belgium", "Kenya", "Spain"]data_json= json.dumps(data["countries"])&nbsp;res = [item for item in index_list if item not in data_json]&nbsp;print(res)结果:['Germany', 'USA', 'Ireland', 'Kenya', 'Spain']

繁星点点滴滴

这是熊猫索引的一种方法。我们不需要循环(或列表理解),因为 Index 包含一个difference()方法。import pandas as pddata = {"countries": ["Australia", "France", "Belgium"]}index_list = ["Germany", "USA", "Ireland", "Australia", "France",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Belgium", "Kenya", "Spain"]result = pd.Index(index_list).difference(data['countries']).to_list()print(result)['Germany', 'Ireland', 'Kenya', 'Spain', 'USA']
随时随地看视频慕课网APP

相关分类

Python
我要回答