如何将列表中的所有数字变为负数? [英] How to turn all numbers in a list into their negative counterparts?

查看:620
本文介绍了如何将列表中的所有数字变为负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如将[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)

当我希望一个为正而另一个为负时,这将打印两个相同的列表.

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)

给予

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

这篇关于如何将列表中的所有数字变为负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆