我在遍历字典键的值并执行数学运算时遇到问题,其中每个键都有不同数量的值:
fruits = {
"banana": [4,5],
"apple": 2,
"orange":1.5,
"pear": 3
}
我想从代码中得到什么(即我理想的作品):
banana [8, 10]
apple 4
orange 3.0
pear 6
我想将每个键中的每个整数乘以 (*) 2。我尝试了以下操作,但无法正确执行:
for fruit, price in fruits.items():
print(fruit, price*2)
for i in price:
print(fruit, i*2)
...但无济于事:这会产生:
banana [4, 5, 4, 5]
banana 8
banana 10
apple 4
好的,所以我试过这个:
for fruit, price in fruits.items():
#print(type(price))
if len(fruit)>0:
print(price*2)
elif len(fruit) == 0:
print(price*2)
它产生了这个:
[4, 5, 4, 5]
4
3.0
6
这甚至可能吗?
任何答案将不胜感激。
亲切的问候,
A. 史密斯
如果列表是例外而不是规则,那么您可以使用try
/except
如下:
def multiplier(x, n):
try:
return float(x)*n
except TypeError:
return [i*n for i in x]
res = {k: multiplier(v, 2) for k, v in fruits.items()}
print(res)
{'banana': [8, 10], 'apple': 4.0, 'orange': 3.0, 'pear': 6.0}
或者,collections.Iterable
如果您希望显式测试可迭代对象,则可以使用:
from collections import Iterable
def multiplier(x, n):
return [i*n for i in x] if isinstance(x, Iterable) else x*n
然后,对于格式化的输出,您可以迭代结果:
for k, v in res.items():
print(k, v)
banana [8, 10]
apple 4.0
orange 3.0
pear 6.0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句