简体   繁体   中英

Get a list with tuple unpacking in a function

I have a given function that takes different inputs (example):

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

Then, this for loop:

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

Which works like this:

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

I want to run it for i in range(n) and get a list of lists as an 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')]

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

If it helps of something, full code:

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)

you need to use a temporary list, which saves the result of one loop and then add those result to the final list and in next loop it intialise itself and then again save result from next triples

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)

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