简体   繁体   English

如何使用列表作为参数运行函数?

[英]How to run functions using lists as the parameters?

So say I have two lists, 假设我有两个清单,

a=[x,y,....z] and b=[x1,y1,...z1] a=[x,y,....z]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? 如何使函数使用列表a和b中的第一项,然后使用列表a和b中的第二项,直到列表末尾? (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. 我是列表中的第一,第二,第n个项目。

you can use zip to access 2 list items simultaneously: 您可以使用zip来同时访问2个列表项:

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. 您可以按索引访问项目,尽管user3的解决方案更为优雅。

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. 为了扩展user3的答案,我创建了一个快速演示函数来演示它的工作原理。

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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