Python中List值的绝对值

2024-03-29 05:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我只希望a[0][0]值变成它们的abs值。创建新列表对我来说是个不错的选择。


Tags: 列表副本absaustria
2条回答
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)

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

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']

相关问题 更多 >