簡體   English   中英

在 function 中獲取帶有元組解包的列表

[英]Get a list with tuple unpacking in a function

我有一個給定的 function 接受不同的輸入(示例):

def myfunction(x, y, z):
    a = x,y,z
    return a

然后,這個for循環:

tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]
for tripple in tripples:
    lst.append(myfunction(*tripple))
lst

像這樣工作:

[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]

我想i in range(n)運行它並獲取列表列表作為 output,

for i in range(3):
    for tripple in tripples:
        lst_lst.append(myfunction(*tripple))
lst_lst

Output:

[('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm'),
 ('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm'),
 ('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm')]

所需的 output:

[[('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm')],
 [('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm')],
 [('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm')]]

如果它有幫助,完整的代碼:

def myfunction(x, y, z):
    a = x,y,z
    return a

lst = []
lst_lst = []
tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]
for tripple in tripples:
    lst.append(myfunction(*tripple))
for i in range(3):
    for tripple in tripples:
        lst_lst.append(myfunction(*tripple))
lst_lst
def myfunction(x, y, z):
    a = x,y,z
    return a

lst = []
tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]

for i in range(3):
    lst_lst = []
    for tripple in tripples:
        lst_lst.append(myfunction(*tripple))

    lst.append(lst_lst)

print(lst)

您需要使用一個臨時列表,它保存一個循環的結果,然后將這些結果添加到最終列表中,並在下一個循環中初始化自身,然后再次保存下一個三元組的結果

def myfunction(x, y, z):
    a = x,y,z
    return a

lst = []
lst_lst = []
tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]
for tripple in tripples:
    lst.append(myfunction(*tripple))
for i in range(3):
    tmp =[]
    for tripple in tripples:
        tmp.append(myfunction(*tripple))
    lst_lst.append(tmp)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM