Python 如何将负转换为正?

Python 如何将负转换为正?,python,Python,结果是: 迈克和汤姆分别是20岁和21岁,身高和体重相差5厘米和-5公斤 汤姆和爱丽丝分别是21岁和19岁,身高和体重相差10厘米和-20公斤 爱丽丝和左图分别是19、23岁,身高和体重分别为-17厘米和30公斤 如何将-17和-30转换为17和30 我知道这一定是因为: students = [ {'name': 'Mike', 'age': 20, 'height': 182, 'weight': 77}, {'name': 'Tom', 'age': 21, 'height

结果是:

迈克和汤姆分别是20岁和21岁,身高和体重相差5厘米和-5公斤 汤姆和爱丽丝分别是21岁和19岁,身高和体重相差10厘米和-20公斤 爱丽丝和左图分别是19、23岁,身高和体重分别为-17厘米和30公斤 如何将-17和-30转换为17和30

我知道这一定是因为:

students = [
    {'name': 'Mike', 'age': 20, 'height': 182, 'weight': 77},
    {'name': 'Tom', 'age': 21, 'height': 177,  'weight': 72},
    {'name': 'Alice', 'age': 19, 'height': 167,  'weight': 52},
    {'name': 'Left', 'age': 23, 'height': 184, 'weight': 82},
]

for i in range(len(students)-1):
    name = students[i]['name']
    age = students[i]['age']
    height = students[i]['height']
    weight = students[i]['weight']

    next_name = students[i+1]['name']
    next_age = students[i+1]['age']
    next_height = students[i+1]['height']
    next_weight = students[i+1]['weight']
 
    difference_height = height - next_height
    difference_weight = weight - next_weight

    print("{} and {} are {}, {} and the difference in height and weight are {}cm an 
{}kg".format(name, next_name, age, next_age, difference_height, difference_weight))
但是我不知道如何修改它。

当你想要绝对值时,使用abs

difference_height = height - next_height
difference_weight = weight - next_weight
此外,您可以使用f字符串而不是格式,我发现它更易于阅读:

a = -5
b = 6
abs(a)
# 5
abs(b)
# 6

您可以使用abs内置功能。abs返回给定数字的绝对值

 print(f"{name} and {next_name} are {age}, {next_age} and the difference in height and weight are {abs(difference_height)}cm and {abs(difference_weight)}kg")
我将abs添加到差异变量中

您可以使用内置函数:

print("{} and {} are {}, {} and the difference in height and weight are {}cm an: {}kg".format(name, next_name, age, next_age, abs(difference_height), abs(difference_weight)))
可以使用absvalue获取数字的绝对值。
difference_height = abs(height - next_height)
difference_weight = abs(weight - next_weight)