簡體   English   中英

如何將列表中的所有數字轉換為負數?

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

我正在嘗試將正數列表轉換為在 python 3.3.3 中具有相同值的負數列表

例如將[1,2,3]變成[-1,-2,-3]

我有這個代碼:

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)

當我想要一個為正而一個為負時,這會打印兩個相同的列表。

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

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

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

如果要就地修改列表:

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

您可以使用 numpy 包並執行numpy.negative()

還有這個方法:

請注意,這僅在所有數字開始為正時才有效。 它不會影響 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]

對於大列表,您可能會更好地使用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)

使用maplambda來做到這一點,就像 Python 專家一樣......

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]

我打算使用map提供另一種解決方案:

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

雖然我想看看速度與簡單的理解以及與 numpy 的對比,雖然它取決於本機解決方案的列表長度,但 numpy 是處理大型數據集的方法:

在此處輸入圖片說明

復制情節的代碼:

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)",
)

球拍:

enter code here

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM