简体   繁体   English

Python函数根据用户输入生成数字列表

[英]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. 您可以将每个项目的值乘以-1来获得负数。

>>> 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 保持00

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: 您需要做的就是获取列表中每个项目的“逆”, map会为您完成:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM