![](/img/trans.png)
[英]How In a python list select the positive numbers values and multiply otherwise return the same value without modified the order on the list?
[英]Return positive numbers of a list in python
我是python的新手。 我想知道如何返回并将下面的列表转换为正数。 那会
打印:
[1、5、2、10]
def func(a):
return abs(a)
print func(a=[1,-5,2,-10])
您想为每个元素调用一次abs
函数,并获取由此产生的列表。 这正是map
的用途:
return map(abs, a)
您还可以使用列表理解:
return [abs(n) for n in a]
使用列表理解 :
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, -5, 2, -10]
>>> b = [abs(x) for x in a]
>>> print b
[1, 5, 2, 10]
>>>
正如Claudiu指出的那样,标准库中的map
函数也将起作用。 但是,Python社区倾向于在可能的情况下使用列表推导,因为它通常使代码更易于阅读。
这是更详细的答案:
def func(a):
for item in a:
yield abs(a)
print list(func(a=[1,-5,2,-10]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.