Python 如何将列表中的所有数字转换为负数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26045779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:57:33  来源:igfitidea点击:

How to turn all numbers in a list into their negative counterparts?

pythonpython-3.xlistnegative-number

提问by SamRob85

I am trying to turn a list of positive numbers into a list of negative numbers with the same value in python 3.3.3

我正在尝试将正数列表转换为在 python 3.3.3 中具有相同值的负数列表

For example turning [1,2,3]into [-1,-2,-3]

例如[1,2,3]变成[-1,-2,-3]

I have this code:

我有这个代码:

xamount=int(input("How much of x is there"))
integeramount=int(input("How much of the integer is there"))
a=1
lista=[]
while(a<=integeramount):
    if(integeramount%a==0):
        lista.extend([a])
    a=a+1
listb=lista
print(listb)
[ -x for x in listb]
print(listb)

This prints two identical lists when I want one to be positive and one to be negative.

当我想要一个为正而一个为负时,这会打印两个相同的列表。

回答by Anton

The most natural way is to use a list comprehension:

最自然的方法是使用列表推导式:

mylist = [ 1, 2, 3, -7]
myneglist = [ -x for x in mylist]
print(myneglist)

Gives

[-1, -2, -3, 7]

回答by Terry Jan Reedy

If you want to modify a list in place:

如果要就地修改列表:

mylist = [ 1, 2, 3, -7]
print(mylist)
for i in range(len(mylist)):
    mylist[i] = -mylist[i]
print(mylist)

回答by Chris Cochrane

There is also this method:

还有这个方法:

Little note, this will only work if all numbers start positive. It won't affect 0. If you have negative numbers you don't want changing you need to add the IF statement below.

请注意,这仅在所有数字开始为正时才有效。它不会影响 0。如果您有不想更改的负数,则需要添加下面的 IF 语句。

if num < 0: continue
numbers = [1, 2, 3, 4 ,5]
for num in numbers:
    numbers[num-1] = num - (2*num)


numbers
[-1, -2, -3, -4, -5]

回答by XTZ

You can use the numpy package and do numpy.negative()

您可以使用 numpy 包并执行 numpy.negative()

回答by Rémi Baudoux

For large list, you will probably better use numpy

对于大列表,您可能会更好地使用 numpy

import numpy as np

a=np.array([1,2,3,4])

# result as a numpy array
b=-a

# can be casted back to list
c=list(b)