将pythonic循环转换为传统循环

2024-03-28 16:06:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的初学者,我有一个问题:考虑到以下几点:

np.asarray([self.simulate(c) for c in challenges])

我想把它分解成传统的编码方式。我能说它相当于:

for c in challenges:
    y = self.simulate(c)
    y = np.asarray[y]

谢谢你。你知道吗


Tags: inselffornp传统asarraychallenges初学者
2条回答

它不是“pythonic循环”,而是list comprehension。你知道吗

等价物是:

items = []
for c in challenges:
    items.append(self.simulate(c))

nparr = np.asarray(items)

你的方法的问题是你没有建立一个列表,比如这个列表。相反,您只是从np.asarray索引一个项目,而从不保存值。此外,您甚至不想索引np.asarray,而是希望将一个列表传递给它的构造函数。你知道吗

您需要创建一个临时列表,以便在每次challenges的迭代中保存self.simulate(c)的返回值,并将该列表传递给np.asarray

temp = []
for c in challenges:
    temp.append(self.simulate(c))
array = np.asarray(temp)

另外,为了让您知道,您所指的“pythonic循环”通常称为list comprehension。”Pythonic”只是我们Python社区成员用来描述Python语言及其理想的一个名称。你知道吗

相关问题 更多 >