Python 带有zip函数的For循环只工作一次
函数do_math()应该迭代列表中的数字和操作。每个operations元素在do_math中定义,并应应用于相应的numbers元素。但是,循环只运行一次,然后停止。有什么想法吗Python 带有zip函数的For循环只工作一次,python,Python,函数do_math()应该迭代列表中的数字和操作。每个operations元素在do_math中定义,并应应用于相应的numbers元素。但是,循环只运行一次,然后停止。有什么想法吗 from math import sqrt def do_math(numbers, operations): for i, j in list(zip(numbers, operations)): if j == "Root": return
from math import sqrt
def do_math(numbers, operations):
for i, j in list(zip(numbers, operations)):
if j == "Root":
return sqrt(i)
elif j == "Square":
return i**2
elif j == "Nothing":
return i
numbers = [2, 9, 25, 6, -3]
operations = ["Square", "Root", "Square", "Root", "Nothing"]
print(do_math(numbers, operations))
您正在使用
return
,它将在循环到达该语句后退出循环。所以我想你是在寻找心爱的yield
from math import sqrt
def do_math(numbers, operations):
for i, j in zip(numbers, operations):
if j == "Root":
yield sqrt(i)
elif j == "Square":
yield i**2
elif j == "Nothing":
yield i
numbers = [2, 9, 25, 6, -3]
operations = ["Square", "Root", "Square", "Root", "Nothing"]
#generated is an object at the moment: <generator object do_math at 0x7fe3c0561d60>
generated = do_math(numbers, operations)
#iterate through that
for i in generated:
print(i)
另请注意:
对于列表中的x,y(zip(a,b))
与zip(数字,操作)中的i,j的相同您的大多数分支返回某些内容,这将立即结束循环并退出调用函数。您可能需要类似于result=[]
,result.append(sqrt(i))
等的内容,返回结果
。这是否意味着zip已经自己创建了一个(元组)列表,并且i,j对应于两个元组元素?我认为我必须首先使用list(),因为我在另一个线程中看到了这一点(尽管问题并不完全相同)。
4
3.0
625
2.449489742783178
-3