用Python编写循环的方法 [英] Pythonic way to write a loop
本文介绍了用Python编写循环的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表:a = [1, 2, 3]
和b = [4, 5, 6]
.
我在python中使用了两个循环,从a
的每个元素中减去b
的每个元素.
I have used two loops in python to subtract each element of b
from each element of a
.
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')方法.
However, I would like to know if there is more elegant('pythonic') way to do it.
推荐答案
无需使用索引.您可以遍历这些值.
There is no need to use an index. You can iterate over the values.
a = [1, 2, 3]
b = [4, 5, 6]
result = []
for x in a:
for y in b:
result.append(x - y)
pythonic方式将是列表理解.
The pythonic way would be a list comprehension.
a = [1, 2, 3]
b = [4, 5, 6]
result = [x - y for x in a for y in b]
请记住,您应该在真实代码中为a
,b
,x
和y
使用有意义的名称.
Please bear in mind that you should use meaningful names for a
, b
, x
and y
in real code.
这篇关于用Python编写循环的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文