简体   繁体   中英

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

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.

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]

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)

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

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]

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)

Use map and lambda to do this, just like a Python pro...

mylist = [1, 2, 3, 4, 5]
mylist = list(map(lambda x: -x, mylist))  # Or "lambda x: x*-1"
print(mylist)  # [-1, -2, -3, -4, -5]

I was going to offer another solution using map :

>>> from operator import neg
>>> list(map(neg, data))

Although I wanted to see the speed vs just the simple comprehension as well as vs numpy, and while it depends on the length of the list for the native solutions, numpy is the way to go for large datasets:

在此处输入图片说明

Code for replicating plot:

import perfplot
import numpy as np
from operator import neg

def list_comp(data): return [ -x for x in data]
def map_neg(data): return list(map(neg, data))
def np_neg(data): return np.negative(data)

perfplot.save(
    "argsort.png",
    setup=lambda n: np.random.rand(n),
    kernels=[list_comp, map_neg, np_neg],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(data)",
)

FOR RACKET:

enter code here

(define (negativelist lst) (cond [(empty? lst) '()] [(cons (* -1 (first lst))(negativelist (rest lst)))]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM