我有一个字典列表-
"produce": [
{
"name": "carrot",
"type": "vegetable",
"price": 10.0,
"units": "KG"
},
{
"name": "potato",
"type": "stem tuber",
"price": 2.0,
"units": "KG"
},
{
"type": "fruit",
"price": 5.0,
"units": "KG"
}
]
如果类型是水果或块茎,我需要获得最低的价格。我收到类型错误-
TypeError: 'float' object is not iterable
我有以下代码-
for m in produce:
if ((m.get('type') == 'stem tuber') or
(m.get('type') == 'fruit')
):
fPrice = min(m['price'])
我在fPrice = min(m['price'])
上收到错误消息。
我不知如何解决此问题。有人可以帮忙吗?我需要获得5.0
和2.0
中最低的价格,所以答案应该是2.0
。
答案 0 :(得分:1)
出现错误是因为您要给run
赋予单个数字,而overflow-wrap: break-word;
word-wrap: break-word;
-webkit-hyphens: auto;
-ms-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
想要一个min()
,例如min
。我们该如何解决?
假设您有这样的字典:
iterable
参加
list
该建立列表理解了!
您要遍历列表mydict = {"produce": [
{
"name": "carrot",
"type": "vegetable",
"price": 10.0,
"units": "KG"
},
{
"name": "potato",
"type": "stem tuber",
"price": 2.0,
"units": "KG"
},
{
"type": "fruit",
"price": 5.0,
"units": "KG"
}
]}
中的项目。
produce = mydict['produce']
然后,您要检查类型是否在某些字符串集中。
produce
然后,您要提取其价格。如果没有价格,则0似乎是合理的默认值!
[for m in produce]
然后您要查找分钟数
[for m in produce if m.get('type') in {'stem tuber', 'fruit'}]
您还可以摆脱[m.get('price', 0) for m in produce if m.get('type') in {'stem tuber', 'fruit'}]
周围的方括号,它变成生成器表达式,如下面的wjandrea's answer所述!
重新。 “如何处理列表理解中没有茎茎或水果类型的记录的情况”
您可以像这样将另一个项目添加到列表中:
min([m.get('price', 0) for m in produce if m.get('type') in {'stem tuber', 'fruit'}])
大概,没有东西要花-1(最低为0)。 然后,如果您得到-1,您将不知道匹配的内容。
答案 1 :(得分:1)
您正在将单个价格提供给min
,这是行不通的。而是提供iterable的价格。您可以使用生成器表达式:
low = min(
m['price']
for m in produce
if m.get('type') in {'stem tuber', 'fruit'}
)
print(low) # -> 2.0
如果它可以帮助您更好地理解,这就像使用列表理解然后将列表提供给min
,但更直接。
prices = [
m['price']
for m in produce
if m.get('type') in {'stem tuber', 'fruit'}
]
low = min(prices)
print(low) # -> 2.0
要处理没有匹配价格的情况,请将min
节包装在try
块中,然后使用except ValueError
。举例来说,让我们使用现有数据,但假设您正在寻找葫芦的最低价格:
try:
low = min(
m['price']
for m in produce
if m.get('type') in {'gourd'}
)
except ValueError:
print('No matching prices')
import sys
sys.exit(1)
请参见Python教程中的Handling Exceptions。
顺便说一句,如果您需要更好的错误消息打印,请查看logging
。