gpt4 book ai didi

python - 列表理解,如果不在第二个列表中则有值(value)

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:40 25 4
gpt4 key购买 nike

如果周存在于 sales else 0 中,是否可以使用列表理解来获取每周的销售额?

weeks = [{'week': 31}, {'week': 32}, {'week': 33}, 
{'week': 34}, {'week': 35}, {'week': 36}]
weeks = [x['week'] for x in weeks]

sales = [
{'week': 32, 'sales': 1167.26},
{'week': 33, 'sales': 1373.61},
{'week': 36, 'sales': 1491.43},
]

expected = [0, 1167.26, 1373.61, 0, 0, 1491.43]

最佳答案

您可以根据 sales 创建一个字典,用作查找 weeks 中的每一周:

weeks = [{'week': 31}, {'week': 32}, {'week': 33}, 
{'week': 34}, {'week': 35}, {'week': 36}]

sales = [
{'week': 32, 'sales': 1167.26},
{'week': 33, 'sales': 1373.61},
{'week': 36, 'sales': 1491.43},
]
_sales = {i['week']:i['sales'] for i in sales}
results = [_sales.get(i['week'], 0) for i in weeks]

输出:

[0, 1167.26, 1373.61, 0, 0, 1491.43]

关于python - 列表理解,如果不在第二个列表中则有值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52556720/

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