python列表过滤技巧
2018-04-06 10:59
295 查看
问题:
有一个列表,a = ['a', 'b', '\n ', 'c', '\n ', 'd'],要求一句话输出['a', 'b', 'c', 'd']
一句话:(python3)
list(filter(str.strip, a))
其实就是Python的高阶函数filter
还有其他的高阶函数map,reduce...
map的例子:
def f(x):
return x * x
print(list(map(f, [-2, 5, -6])))
运行结果:[4, 25, 36]
reduce的例子:
from functools import reduce
def f(x, y):
return x + y
print(reduce(f, [-2, 5, -6], 100))
运行结果:97
filter的例子:
def is_odd(x):
return x % 2 == 1
arr = [1, 4, 6, 7, 9, 12, 17]
print(list(filter(is_odd, arr)))
运行结果:[1, 7, 9, 17]
更多的使用方法查看Python文档哦~~~
有一个列表,a = ['a', 'b', '\n ', 'c', '\n ', 'd'],要求一句话输出['a', 'b', 'c', 'd']
一句话:(python3)
list(filter(str.strip, a))
其实就是Python的高阶函数filter
还有其他的高阶函数map,reduce...
map的例子:
def f(x):
return x * x
print(list(map(f, [-2, 5, -6])))
运行结果:[4, 25, 36]
reduce的例子:
from functools import reduce
def f(x, y):
return x + y
print(reduce(f, [-2, 5, -6], 100))
运行结果:97
filter的例子:
def is_odd(x):
return x % 2 == 1
arr = [1, 4, 6, 7, 9, 12, 17]
print(list(filter(is_odd, arr)))
运行结果:[1, 7, 9, 17]
更多的使用方法查看Python文档哦~~~
相关文章推荐
- python列表排序方法sort、sorted技巧篇
- Python入门(七):生成列表、条件过滤、多层表达式
- 《Python CookBook2》 第四章 Python技巧 对象拷贝 && 通过列表推导构建列表
- Python过滤列表用法实例分析
- python列表(list)的使用技巧及高级操作
- (原创)输出列表中成员出现的次数(Python技巧)
- python - 列表分组技巧 #写出一段 Python 代码,实现分组一个 list 里面的元素,如 [1,2,3,...100]变成 [[1,2,3],[4,5,6]....]
- python 列表排序方法sort、sorted技巧篇(转自: aben)
- Python 过滤字符串的技巧,map与itertools.imap
- python 列表排序方法sort、sorted技巧篇
- Python 过滤字符串的技巧,map与itertools.imap
- python 函数-映射列表和过滤列表 学习
- python中遍历列表、元组的技巧
- 学习python 遇到的第一个问题 :过滤列表
- Python基础 之 列表常用方法及技巧
- 【python】对列表的过滤, 列表解析,生成器表达式
- Python 过滤列表
- Python 技巧:如何将一个列表list用一句代码改成列表中的列表
- 使用PYTHON列表生成式过滤数据
- Python列表生成器的循环技巧分享