【问题标题】:I have an issue with dictionaries in list我对列表中的字典有疑问
【发布时间】:2021-12-17 17:18:14
【问题描述】:

我需要回答卖了多少公斤黄瓜的问题。我对某一天卖出了多少公斤不感兴趣,但如果你告诉我如何得到它,我会很高兴的。我也想知道如何只打印字典的前一部分(没有工作日)。到目前为止,这是我的答案,有人可以帮我吗?

# listing = [
#     { 'mass' : 20, 'name' : 'onion', 'weekday' : 'monday'},
#     { 'mass' : 10, 'name' : 'garlic', 'weekday' : 'tuesday'},
#     { 'mass' : 40, 'name' : 'carrot', 'weekday' : 'monday'},
#     { 'mass' : 90, 'name' : 'cucumber', 'weekday' : 'saturday'},
#     { 'mass' : 80, 'name' : 'onion', 'weekday' : 'sunday'},
#     { 'mass' : 30, 'name' : 'parslay', 'weekday' : 'sunday'},
#     { 'mass' : 20, 'name' : 'onion', 'weekday' : 'sunday'},
#     { 'mass' : 10, 'name' : 'cucumber', 'weekday' : 'wednesday'},
#     { 'mass' : 1, 'name' : 'garlic', 'weekday' : 'sunday'},
# ]

def list(listing):
    for i in listing:
        print(next(item for item in listing if item["name"] == "cucumber"))
print(list([{ 'mass' : 20, 'name' : 'onion', 'weekday' : 'monday'},{ 'mass' : 10, 'name' : 'garlic', 'weekday' : 'tuesday'},{ 'mass' : 40, 'name' : 'carrot', 'weekday' : 'monday'},{ 'mass' : 90, 'name' : 'cucumber', 'weekday' : 'saturday'},{ 'mass' : 80, 'name' : 'onion', 'weekday' : 'sunday'},{ 'mass' : 30, 'name' : 'parslay', 'weekday' : 'sunday'},{ 'mass' : 20, 'name' : 'onion', 'weekday' : 'sunday'},{ 'mass' : 10, 'name' : 'cucumber', 'weekday' : 'wednesday'},{ 'mass' : 1, 'name' : 'garlic', 'weekday' : 'sunday'}]))
    

【问题讨论】:

  • 您期望的确切输出是什么?
  • 最好呈现所需的输出,因为您要求的不是很清楚。
  • 你最好不要覆盖 list 关键字/函数,而是为你的函数使用另一个名称。

标签: python list dictionary receipt shopping


【解决方案1】:

您可以使用带有条件的小推导:

sum(i['mass'] for i in listing if i['name'] == 'cucumber')

输出:100

您可以添加其他条件,这里的日子需要在周末:

sum(i['mass'] for i in listing
    if i['name'] == 'cucumber' and i['weekday'] in ('saturday', 'sunday'))

输出:90

【讨论】:

    【解决方案2】:

    sum 与适当的条件生成器表达式一起使用:

    def cucu_mass(dcts):
        return sum(dct["mass"] for dct in dcts if dct["name"] == "cucumber")
    

    一些文档:

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 2017-02-22
      • 2019-05-06
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 2018-04-14
      • 2022-11-14
      • 2020-10-17
      相关资源
      最近更新 更多