[英]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)
使用map
和lambda
来做到这一点,就像 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.