Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...