我有一个给定的函数,它接受不同的输入(例如(:
def myfunction(x, y, z):
a = x,y,z
return a
然后,这个循环:
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)
运行它,并获得一个列表列表作为输出,
for i in range(3):
for tripple in tripples:
lst_lst.append(myfunction(*tripple))
lst_lst
输出:
[('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')]
期望输出:
[[('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)