简体   繁体   中英

Python function to make a list of numbers from user input

I am to write code so that when I run the program, user input can write a couple of numbers and return the value of those numbers negated. Example, user calls the function with this:

neg([1, 2, -3, 54, -9])

And that will result in this output:

[-1,  -2,  3,  -54,  9]

I'm having trouble finding the right coding to solve this issue. I'm grateful for all help.

You can multiple the values of each item by -1 to get the negative.

>>> mylist = [-1,2,-3,-4.6,0]
>>> neg_list = [-x for x in mylist]
>>> neg_list
[1, -2, 3, 4.6, 0]

You can see that this works for both positive and negative values within the list. It keeps 0 at 0

lst = [1, 2, -3, 54, -9]

def neg(lst):
    for i in range(len(lst)):
        lst[i] *= -1
    return lst

print neg(lst)

All you need to do is get the "inverse" of each item in the list, map will do just that for you:

In [1]: map(lambda item: -item, [1, 2, -3, 54, -9])
Out[1]: [-1, -2, 3, -54, 9]

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