sha*_*nuo 43 python function list
如何将函数应用于变量输入列表?例如,filter函数返回true值,但不返回函数的实际输出.
from string import upper
mylis=['this is test', 'another test']
filter(upper, mylis)
['this is test', 'another test']
Run Code Online (Sandbox Code Playgroud)
预期的产出是:
['THIS IS TEST', 'ANOTHER TEST']
Run Code Online (Sandbox Code Playgroud)
我知道upper是内置的.这只是一个例子.
mdm*_*dml 58
>>> from string import upper
>>> mylis=['this is test', 'another test']
>>> map(upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']
Run Code Online (Sandbox Code Playgroud)
更简单,你可以使用str.upper而不是从导入string(感谢@alecxe):
>>> map(str.upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']
Run Code Online (Sandbox Code Playgroud)
在Python 2.x中,map通过将给定函数应用于列表中的每个元素来构造新列表.filter通过限制True使用给定函数求值的元素来构造新列表.
在Python 3.x中,map和filter构建迭代器,而非列表,所以如果你使用Python 3.x和要求的清单列表解析的方法会更适合.
ale*_*cxe 52
或者,您可以采取一种list comprehension方法:
>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']
Run Code Online (Sandbox Code Playgroud)
小智 9
有时您需要将函数应用于列表的成员。以下代码对我有用:
>>> def func(a, i):
... a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']
Run Code Online (Sandbox Code Playgroud)
请注意, map()的输出被传递给列表构造函数,以确保列表在 Python 3 中进行转换。返回的填充None值的列表应该被忽略,因为我们的目的是就地转换列表a
| 归档时间: |
|
| 查看次数: |
102120 次 |
| 最近记录: |