Python中列表中值的绝对值
在Python中,怎么把一个列表里的所有值都转换成它们的绝对值呢?我想要一个新的列表,里面的值都是原来列表的绝对值。
a=[['2.40', '1970-1990', 'Austria']]
我只想把 a[0][0]
里的值变成绝对值。创建一个新的列表对我来说是个不错的选择。
2 个回答
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)
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']