簡體   English   中英

如何將值傳遞給作為 Python 中列表項的函數

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

我想在作為列表項的函數中傳遞一個值作為參數。

例如:

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

先謝謝了。

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

你寫

l = [1,2,3,foo]

然后

print l[3](x,y)

為了將foo()的結果存儲在您的列表中,您需要對代碼中的步驟重新排序。 我建議將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)

或者,您可以創建列表,然后向其附加值:

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