3 回答
TA贡献1772条经验 获得超5个赞
您可以将 JSON 数据转换为 list() 并使用列表理解过滤其他数据。
import json
data_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)
TA贡献1828条经验 获得超6个赞
您可以循环遍历所有元素并检查它们是否存在于 json 列表中,而不是过滤器
import json
data = {"countries": ["Australia", "France", "Belgium"]}
index_list = ["Germany", "USA", "Ireland", "Australia", "France", "Belgium", "Kenya", "Spain"]
data_json= json.dumps(data["countries"])
res = [item for item in index_list if item not in data_json]
print(res)
结果:['Germany', 'USA', 'Ireland', 'Kenya', 'Spain']
TA贡献1803条经验 获得超3个赞
这是熊猫索引的一种方法。我们不需要循环(或列表理解),因为 Index 包含一个difference()方法。
import pandas as pd
data = {"countries": ["Australia", "France", "Belgium"]}
index_list = ["Germany", "USA", "Ireland", "Australia", "France",
"Belgium", "Kenya", "Spain"]
result = pd.Index(index_list).difference(data['countries']).to_list()
print(result)
['Germany', 'Ireland', 'Kenya', 'Spain', 'USA']
添加回答
举报