天天看點

python中絕對值怎麼表示_Python中List值的絕對值

a = ['2.40', '1970-1990', 'Austria'] #your old list (with the extra [] removed, they seem not to have a point... If you need them you can easily edit the code appropriately)

b = [] #a new list with the absolute values

for i in range(0, len(a)): #going through each of the values in a

try:

b += [abs(float(a[i]))] #trying to take the absolute value and put it in the new list (I have the float() because it appears that your 2.40 is a string. If you have it as an actual integer or float (such as 2.40 instead of '2.40') you can just use abs(a[i])

except:

b += [a[i]] #if taking the absolute value doesn't work it returns the value on its own.

print(b)