【问题标题】:Convert this single-line nested for loop to multi-line in python在python中将此单行嵌套for循环转换为多行
【发布时间】:2016-09-17 20:23:48
【问题描述】:

我无法理解我在这里修改的代码有什么不同。第一段就来自python documentation.

def product(*args, **kwds):
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

我想编写一段非常相似的代码,但对我们何时实际将产品用于参数中的特定元素有条件,所以我想将result = [x+[y] for x in result for y in pool] 行转换为多行,然后我可以使用我的 if声明之类的。这是我所做的,但是当我运行它时,它似乎陷入了无限循环,或者什么......

def Myproduct(*args, **kwds):
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        for x in result:
            for y in pool:
                result.append(x+[y])
    for prod in result:
        yield tuple(prod)

我想真正了解这里的区别。我已经阅读并认为我得到了this post,但我仍然没有看到在这种情况下如何正确转换,或者为什么它至少不是相同的转换。提前谢谢你。

【问题讨论】:

    标签: python for-loop nested-loops


    【解决方案1】:

    问题是您要添加到您正在迭代的列表中。因此,如果一开始是result = [[]]pools = [1, 2, 3],那么在for x in result 的第一次迭代之后,您的列表将是[[], [] + [1]],那么您将获取第二个元素,等等。

    列表推导是在一行中创建一个新列表,然后将其重命名为映射到结果。

    在修改您正在迭代的列表时要非常小心!

    【讨论】:

      【解决方案2】:

      这是一个等效函数:

      def myproduct(*args, **kwds):
          pools = map(tuple, args) * kwds.get('repeat', 1)
          result = [[]]
          for pool in pools:
              nresult = []
              for x in result:
                  for y in pool:
                      nresult.append(x+[y])
              result = nresult
          for prod in result:
              yield tuple(prod)
      

      注意nresult的创建是为了避免JETM指出的问题。

      【讨论】:

      • 谢谢!我希望我能接受你的两个答案。很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2013-08-09
      • 1970-01-01
      • 2013-06-05
      • 2012-11-06
      相关资源
      最近更新 更多