【发布时间】:2021-04-05 18:19:06
【问题描述】:
我有一个接受不同输入的给定函数(示例):
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) 运行它并获取列表列表作为输出,
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
【问题讨论】:
-
你可以改用
[tripples]*3。 -
@wim 实际代码更复杂。第一条语句说函数只是一个例子,所以
[tripples]*3还不够 -
好的。函数是确定性的吗? (相同的输入 = 相同的输出)
-
不,输入是不同的变量,它返回一个列表,已经有一个接受的答案,谢谢。
标签: python list function tuples iterable-unpacking