Python 中列表中值的绝对值

发布于 2024-12-18 14:49:45 字数 184 浏览 0 评论 0原文

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

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

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

In Python, how do convert all the values in a list to their abs values? I would like a deep copy of the original list with the absolute values.
say

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

I just want a[0][0] values to change into their abs values. Creating new list is a ok option for me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

摘星┃星的人 2024-12-25 14:49:45

我认为一个更干净的例子:

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

A cleaner example I think:

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']
近箐 2024-12-25 14:49:45
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'] #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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文