简体   繁体   中英

Python - Efficiently applying function

I'm prety new to python so my question might be basic but is there a way to change two variables at the same time when using a function. my problem is i currently use a double for loop to do so and it creates a lot of useless values. As we understand better by exemple, here is a rapidly crafted one:

results=[]
Q1=[1,2,3]
P1=[4,5,6]
def findcash(Q,P):
    r=Q/P
    results.append(r)
for i in Q1:
    for j in P1:
        findcash(i,j)

now you see my return vector will have values of 1/4;1/5; 1/6... where in reality i would like Q1 to change when P1changes so results=[1/4 2/5 3/6]

Cheers

You can use the builtin zip

results = [Q/P for Q, P in zip(Q1, P1)]

which is kind of equivalent to this: (not really, but the idea is the same (you know - like a zipper))

for i in range(min(len(Q), len(P))):
     Q = Q1[i]
     P = P1[i]
     ...
results=[]
Q1=[1,2,3]
P1=[4,5,6]
def findcash(Q,P):
    r=Q/P
    results.append(r)
for i,j in zip(Q1, P1):
  findcash(i,j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM