【问题标题】:Get a list with tuple unpacking in a function在函数中获取带有元组解包的列表
【发布时间】: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


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

    您需要使用一个临时列表,它保存一个循环的结果,然后将这些结果添加到最终列表中,并在下一个循环中初始化自身,然后再次保存下一个三元组的结果

    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)
    

    【讨论】:

    • 为什么需要第一个循环?
    • @BryanWoo 我只是拿了 OP 完整代码并修改了后面和使用的部分。第一个循环可以去掉,答案在lst_lst list 中。
    猜你喜欢
    • 1970-01-01
    • 2015-12-30
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2021-10-28
    • 2015-07-24
    相关资源
    最近更新 更多