需求:快速实现一个列表数据的叠加,跌乘等操作。
问题描述
代码如下
# coding=utf-8
# 作者:Administrator
# 创建时间:2022 2022/5/9 9:32
# IDE:PyCharm
# 描述:
# compress: 按照真值表筛选元素,返回条件是真值的数据
# dropwhile: 按照条件筛选,丢弃掉第一次不符合条件时之前的所有元素
# takewhile: 只要元素为真就返回,第一次遇到不符合的条件就退出。
# filterfalse : 保留筛选为false的数据
# groupby 输出符合条件和不符合条件的数据,两个都输出
# islice 切换 ,开始值,结束的值,跨度
# starmap 同map 不多说,传入处理函数,和数据,返回处理后的数据列表
# tee 从一个可迭代对象中返回 n 个独立的迭代器
import operator
from itertools import compress, dropwhile, takewhile, filterfalse, groupby, islice,tee
# iteratortools.compress(data, selectors) ,data是数据,selectors筛选的条件
list1 = [1, 2, 3, 4]
list2 = [1, 0, 1, 0] # 1 真,0假
list3 = [True, True, False, False]
print(list(compress(list1, list2))) # [1, 3]
print(list(compress(list1, list3))) # [1, 2]
# iteratortools.dropwhile(predicate, iteratorable) predicate 条件函数,iteratorable data数据
list4 = [1, 2, 3, 4, 5, 6, 7, 1]
print(list(dropwhile(lambda x: x < 3, list4))) # 第一个值不符合要求之后,就返回后面剩下的所有数据[3, 4, 5, 6, 7, 1]
print(list(takewhile(lambda x: x < 3, list4))) # 第一个值不符合要求之后,就返回前面剩下的所有数据 [1, 2]
print(list(filterfalse(lambda x: x < 3, list4))) # 所有false的数值[3, 4, 5, 6, 7]
for one, two in groupby(list4, lambda x: x < 3):
print(one, list(two))
# True [1, 2]
# False [3, 4, 5, 6, 7]
# True [1]
mylist = [x for x in range(100)]
myr = islice(mylist, 0, 40, 10)
print(list(myr)) # [0, 10, 20, 30]
# 生成三个 mylist
for one in tee(mylist,3):
print(list(one))
解决方案:
强大而有用的工具内置迭代工具 【叠加,叠乘等快速操作】,可以让你的代码简单,可读性强



