【问题标题】:How to return full list of arrays separately?如何分别返回完整的数组列表?
【发布时间】:2016-05-31 13:49:56
【问题描述】:

我在这里有一个名为factors 的函数,我用它来定义第二个函数permutations。首先factors这里:

def factors(x):
    factors = []
    for x in range(1,x+1):
        factors.append(x)
    return factors

我使用的下一段代码是:

import itertools as it

def permutations(x):
    for p in it.permutations(factors(x)):
        return(np.array(p))

当我尝试运行 permutations(3) 时,它返回:

array([1 2 3])

我似乎无法返回所有行,而是只获取数组的第一行。我尝试打印它,并且打印工作:

import itertools as it

for p in it.permutations(factors(3)):
    print(np.array(p))

这会返回:

[1 2 3]
[1 3 2]
[2 1 3]
[2 3 1]
[3 1 2]
[3 2 1]

我认为这与我返回的方式有关,因为我只要求第一个数组,我不会以某种方式对其进行迭代以显示所有数组。我希望它返回所有数组作为对我的函数的返回。

【问题讨论】:

    标签: python arrays return


    【解决方案1】:

    当你的函数遇到 return 语句时,它会永远返回。把return改成yield做一个生成器:

    def permutations(x):
        for p in it.permutations(factors(x)):
            yield np.array(p)
    

    演示:

    >>> list(permutations(3))
    [array([1, 2, 3]), array([1, 3, 2]), array([2, 1, 3]), array([2, 3, 1]), array([3, 1, 2]), array([3, 2, 1])]
    

    另一件事:您的factors 函数毫无意义。你可以使用range 来做同样的事情,例如:

    >>> range(1, 5)
    [1, 2, 3, 4]
    

    所以行

    for p in it.permutations(factors(x)):
    

    应该写成

    for p in it.permutations(range(1, x+1)):
    

    最后,如果你使用的是 Python 3.3 或更新版本,你可以使用yield from 语法:

    def permutations(x):
        yield from map(np.array, it.permutations(range(1, x+1)))
    

    【讨论】:

    • 我试过yield,它返回:<generator object permutations at 0x10db4cf68>。有什么想法吗?
    • @MichaelHwang 从生成器对象中列出。 list(permutations(3))
    • 我将因子保留为函数,因为我需要在其他地方调用它,但我绝对可以通过将其定义为 range(1,x+1) 来简化它。谢谢。
    • @MichaelHwang 没问题
    【解决方案2】:

    return 语句立即终止函数并返回给调用者。在您的情况下,这意味着它永远不会进入第二次循环迭代。

    而不是 for 循环:

    for p in it.permutations(factors(x)):
        return(np.array(p))
    

    尝试使用list comprehension 构造一个数组:

    return [np.array(p) for p in it.permutations(factors(x))]
    

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 2020-02-13
      相关资源
      最近更新 更多