这有什么方法可以检查我的字典中是否有负值(只有整数)? 如果是,将所有负值更改为正值? 例如:
D = {'Milk': -5, 'eggs': 144, 'flour': -10, 'chocolate': -2, 'yeast': 5, 'Cornflower': 3}
我想得到:
D = {'Milk': 5, 'eggs': 144, 'flour': 10, 'chocolate': 2, 'yeast': 5, 'Cornflower': 3}
最佳答案
遍历字典然后使用 abs()
内置函数:
D = {'Milk': -5, 'eggs': 144, 'flour': -10, 'chocolate': -2, 'yeast': 5, 'Cornflower': 3}
for key, value in D.items():
D[key] = abs(value)
print(D)
输出:
{'yeast': 5, 'Milk': 5, 'flour': 10, 'chocolate': 2, 'eggs': 144, 'Cornflower': 3}
如果你想在值为负数时做其他事情,使用 if
语句:
D = {'Milk': -5, 'eggs': 144, 'flour': -10, 'chocolate': -2, 'yeast': 5, 'Cornflower': 3}
for key, value in D.items():
if value < 0:
print('{} is negative'.format(key))
D[key] = abs(value)
print(D)
输出:
chocolate is negative
Milk is negative
flour is negative
{'chocolate': 2, 'Cornflower': 3, 'Milk': 5, 'flour': 10, 'yeast': 5, 'eggs': 144}
关于Python将字典中的负值更改为正值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61307403/