【问题标题】:Function does not store all the output函数不存储所有输出
【发布时间】:2019-11-15 10:30:42
【问题描述】:

我有以下清单,

p=[list(['a', 'b', 'c']), list(['d', 'e'])]

我想制作每个元素的子集(大小为 2)并列出它们,这将给出如下输出:

[[('a', 'b'), ('a', 'c'), ('b', 'c')],[('d', 'e')]]

为了实现这一点,我编写了以下函数,

def x(m,n):
    for i in x:
        z=list(itertools.combinations(i, n))
    return(z)

然而,当我申请 z(m,2) 时,我只得到最后一个元素:

[('d', 'e')]

我想知道我做错了什么?

【问题讨论】:

  • x是函数名,为什么还要使用for i in x?这似乎不正确......
  • 每次迭代都会覆盖z
  • 这样的代码无法运行,请修复它,然后执行z.append(list(itertools.combinations(i, n))) 其中z 是一个列表
  • 这看起来不像一个列表。看起来你有一个 NumPy 数组并且你假装它是一个列表。

标签: python arrays list function


【解决方案1】:

这是因为您每次都设置 z 而不是附加它:

def x(m,n):
    z = []
    for i in m:
        z.append(list(itertools.combinations(i, n)))
    return(z)

产量:

[[('a', 'b'), ('a', 'c'), ('b', 'c')], [('d', 'e')]]

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 1970-01-01
    • 2011-10-04
    • 2020-01-07
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多