简体   繁体   English

如何将值传递给作为 Python 中列表项的函数

[英]How to pass values to a function which is a list item in Python

I want to pass a value as argument in a function which is a list item.我想在作为列表项的函数中传递一个值作为参数。

For example:例如:

def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )


l = [1,2,3, foo('want values here as arguments')] 

def foo_bar():
    x = 0, y = 1
    print(“want to pass x and y inside: “ , l[3])

Thanks ahead.先谢谢了。

 def foo(arg1, arg2):
    print("Something is happening here", arg1, arg2 )


l = [1,2,3, foo] 

def foo_bar():
    x = 0
    y = 1
    print("want to pass x and y inside: " , l[3](x,y))

You write你写

l = [1,2,3,foo]

and later然后

print l[3](x,y)

In order to store the result from foo() in your list, you need to reorder the steps in your code.为了将foo()的结果存储在您的列表中,您需要对代码中的步骤重新排序。 I recommend storing the return result from foo() as a variable:我建议将foo()的返回结果存储为变量:

def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )



def foo_bar():
    x = 0
    y = 1
    z = foo(x, y)
    l = [1,2,3, z] 
    print(l)

Alternatively, you can create the list and then append values to it:或者,您可以创建列表,然后向其附加值:

def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )


l = [1,2,3] 


def foo_bar():
    x = 0
    y = 1
    z = foo(x, y)
    l.append(z)
    print(l)

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

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