简体   繁体   中英

How to run functions using lists as the parameters?

So say I have two lists,

a=[x,y,....z] and b=[x1,y1,...z1]

and a function that has parameters of these two lists:

def examplefunction(a,b)

How could I make it so that the function uses the first items in lists a and b, then the second items in lists a and b, until the end of the list? (And each list has the same number of items)

Would I do something like:

def main():
    for i in range(len(a)):
        examplefunction(a[i],b[i])

with i being the 1st, 2nd, ... nth item in the list.

you can use zip to access 2 list items simultaneously:

for firstlistitem,secondlistitem in zip(a,b):
    .....

Although not sure what you're asking for, but
Your example function would look like this:

def examplefunction(a,b):
    list_s = len(a)
    for i in range(list_s):
        item_a = a[i]
        item_b = b[i]

You can access the items by index, though user3's solution is more elegant.

a = [1,2,3]
b = [4,5,6]
for index, value in enumerate(a):
    print value, b[index]
[examplefunction(aa, bb) for (aa, bb) in zip(a,b)]

会生成结果列表,或使用()而不是[]获得生成器。

To expand on user3's answer I created a quick demo function to demonstrate that it works.

>>> def foo(a, b):
...     print('{} - {}'.format(a, b))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> l
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> for a, b in zip(l, lst):
...     foo(a, b)
... 
10 - 1
9 - 2
8 - 3
7 - 4
6 - 5
5 - 6
4 - 7
3 - 8
2 - 9
1 - 10

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