Python中List的值的绝对值

时间:2011-11-29 02:26:43

标签: python

在Python中,如何将列表中的所有值转换为其abs值?我想要一个带有绝对值的原始列表的深层副本。 说

a=[['2.40', '1970-1990', 'Austria']]

我只想将a[0][0]值更改为其abs值。创建新列表对我来说是一个不错的选择。

2 个答案:

答案 0 :(得分:2)

我认为一个更清洁的例子:

a=[['2.40', '1970-1990', 'Austria']]

b = []

for i in a[0]:
    try:
        b.append(abs(float(i)))
    except: 
        b.append(i)


print(b)

[2.4, '1970-1990', 'Austria']

答案 1 :(得分:1)

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)