我需要回答賣了多少公斤黃瓜的問題。我對特定日期售出多少公斤不感興趣,但如果你告訴我如何獲得它的公式,我會很高興。我也想知道如何只列印字典的前一部分(沒有作業日)。到目前為止,這是我的答案,某人可以幫助我嗎?
# 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'}]))
uj5u.com熱心網友回復:
使用sum與適當的條件生成器運算式:
def cucu_mass(dcts):
return sum(dct["mass"] for dct in dcts if dct["name"] == "cucumber")
一些檔案:
sum- 生成器運算式
uj5u.com熱心網友回復:
您可以使用帶有條件的小型理解:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347425.html
下一篇:如何重新排序嵌套串列中的元素?
