gpt4 book ai didi

编写循环的 Pythonic 方式

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:47 24 4
gpt4 key购买 nike

我有两个列表:a = [1, 2, 3]b = [4, 5, 6]

我在 python 中使用了两个循环,从 a 的每个元素中减去 b 的每个元素。

import numpy as np
a = [1, 2, 3]
b = [4, 5, 6]
p = -1
result = np.zeros(len(a)*len(a))
for i in range(0,len(a)):
for j in range(0,len(a)):
p = p + 1
result[p] = a[i] - b[j]

我的结果是正确的:result = [-3., -4., -5., -2., -3., -4., -1., -2., -3.]

但是,我想知道是否有更优雅('pythonic')的方式来做到这一点。

最佳答案

不需要使用索引。您可以迭代这些值。

a = [1, 2, 3]
b = [4, 5, 6]
result = []
for x in a:
for y in b:
result.append(x - y)

Pythonic 方式是列表理解。

a = [1, 2, 3]
b = [4, 5, 6]
result = [x - y for x in a for y in b]

请记住,您应该为 abxy 使用有意义的名称真正的代码。

关于编写循环的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26736277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com