使用cap在python中累积
我有一张单子使用cap在python中累积,python,python-3.x,Python,Python 3.x,我有一张单子 nums=[1,2,4,6] 我想用5的上限来累加这个列表,也就是说,如果累加值超过5的倍数,它应该打印5的倍数值,然后打印该值 预期输出: 1 3 5 7 10 13 编写的代码如下: nums=[1,2,4,6] from itertools import accumulate a= accumulate(nums) for i in a: print(i) 正在打印的输出 1 3 7 13 如何获得所需的输出这里有一个使用生成器表达式的Pythonic方法:
nums=[1,2,4,6]
我想用5的上限来累加这个列表,也就是说,如果累加值超过5的倍数,它应该打印5的倍数值,然后打印该值
预期输出:
1
3
5
7
10
13
编写的代码如下:
nums=[1,2,4,6]
from itertools import accumulate
a= accumulate(nums)
for i in a:
print(i)
正在打印的输出
1
3
7
13
如何获得所需的输出这里有一个使用生成器表达式的Pythonic方法:
In [12]: from itertools import accumulate, chain
In [13]: list(chain.from_iterable((i,) if i < 5
else (next(j for j in range(i, 0, -1) if j%5 == 0), i)
for i in accumulate(nums)))
Out[13]: [1, 3, 5, 7, 10, 13]
演示:
这种方法实际上比基于生成器的方法更快:
In [20]: %timeit list(myaccumulate(nums))
2.65 µs ± 47.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [21]: %timeit list(chain.from_iterable((i,) if i < 5 else (next(j for j in range(i, 0, -1) if j%5 == 0), i) for i in accumulate(nums)))
4.12 µs ± 21.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
[20]中的:%timeit列表(myaccumulate(nums))
每个回路2.65µs±47.9 ns(7次运行的平均值±标准偏差,每个100000个回路)
在[21]中:%timeit list(如果i<5,则为chain.from_iterable((i,)else(如果j%5==0,则为范围(i,0,-1)中的j,如果j%5==0,则为i)中的i,则为累积(nums))中的i)
每个回路4.12µs±21.3 ns(7次运行的平均值±标准偏差,每个100000个回路)
这里有一种手动方式。效率不高,但可读性强。假设您处理的是正数
from itertools import accumulate
nums = [1,2,4,6]
acc = list(accumulate(nums)) # regular accumulation
add = [i for i in range(5, acc[-1], 5) if i not in acc] # multiples of 5 missing
res = sorted(acc + add) # combine results and sort
print(res)
[1, 3, 5, 7, 10, 13]
另一种方法是使用
设置:
add = list(set(range(5, acc[-1], 5)) - set(acc))
我想你也可以做I-I%5
@pault来代替这个范围,但这并没有造成太大的不同。生成器表达式本身已不清楚;)。同意在这种情况下没有很大的差别,但是如果他们在寻找之前10000的倍数,这可能会开始起作用。这可能是最好的答案。但我只希望它可以部分编写。@Python\u newbierange()
不适用于浮动。相反,您可以使用math.ceil
、round
、math.floor
或其他强制转换函数将其转换为整数。范围(5,acc[-1],5)
取决于acc
中最大的元素是最后一个。但是,如果原始列表nums
包含负数,这并不一定是真的…@lkriener,很好的观点,可修复的-但现在我只添加免责声明。
from itertools import accumulate
nums = [1,2,4,6]
acc = list(accumulate(nums)) # regular accumulation
add = [i for i in range(5, acc[-1], 5) if i not in acc] # multiples of 5 missing
res = sorted(acc + add) # combine results and sort
print(res)
[1, 3, 5, 7, 10, 13]
add = list(set(range(5, acc[-1], 5)) - set(acc))