我正在练习使用带有一些循环和ifs的itertool.accumulate
函数。结果,我想要一个单个数字(变量称为"调用"(和每个周期的总和的列表,即 3。
现在,我已经设法获得了两个列表,但不是同时获得。我的意思是,一旦打印了一个列表,它就会变成空。我错过了什么吗?如何打印两个列表?
我将发布带有输出的两个代码,以向您展示我的意思。
第一个代码:它只打印单个值
import random as rnd
import itertools
# variables
a = 5
b = int(1)
########
calls = (
tuple((itertools.accumulate(
a if a > rnd.randint(1, 10) else -a
for i in range(b)
for j in range(2))
)
)
for cycle in range(3)
)
#######
print(list(calls))
print(list(sum(call) for call in calls))
[(5, 0(, (-5,-10(, (5, 0(]
[]
第二个代码:它只打印值的总和 导入随机作为 RND 导入迭代工具
# variables
a = 5
b = int(1)
########
calls = (
tuple((itertools.accumulate(
a if a > rnd.randint(1, 10) else -a
for i in range(b)
for j in range(2))
)
)
for cycle in range(3)
)
#######
print(list(sum(call) for call in calls)
print(list(calls))
[5, -15, 5]
[]
最简单的解决方案:直接将其转换为list
:
calls = list( # only changed here
tuple((itertools.accumulate(
a if a > rnd.randint(1, 10) else -a
for i in range(b)
for j in range(2))
)
)
for cycle in range(3)
)
问题是您在使用以下命令时创建生成器表达式 (PEP 289(:
(... for cycle in range(3))
并且生成器表达式不能重用,它们用于惰性一次性计算。
您也可以使用列表推导[ ... ]
而不是( ... )
:
calls = [
tuple((itertools.accumulate(
a if a > rnd.randint(1, 10) else -a
for i in range(b)
for j in range(2))
)
)
for cycle in range(3)
]