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

时光毁灭记忆、已成空白 提交于 2020-01-09 11:07:26

问题


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

For example turning [1,2,3] into [-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.


回答1:


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]



回答2:


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)



回答3:


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




回答4:


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.

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]



回答5:


For large list, you will probably better use 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)


来源:https://stackoverflow.com/questions/26045779/how-to-turn-all-numbers-in-a-list-into-their-negative-counterparts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!