列表理解中的多个打印功能

时间:2016-08-31 22:07:46

标签: python python-2.7 python-3.x for-loop list-comprehension

这篇文章的目标是在列表理解中放置多个打印功能,以便直观地了解其中发生的事情。

重要说明:

  • 不应用于教育目的之外的其他任何内容并尝试理解代码。
  • 如果你使用的是Python 2.x,你需要添加一个未来的导入(它在我粘贴的代码中),否则打印不会起作用。只有函数才能在列表理解中起作用。 2.x中的打印不作为功能运行。或者......只需切换到Python 3.x.

这是最初的问题:

    ## Using future to switch Print to a function
    from __future__ import print_function 

    reg = []
    for x in [1,2,3]:
        for y in [3,1,4]:
            print('looping through',x,'then',y)
            if x == y:
                print('success',x,y)
                reg.append((x,y))
    print(reg)

这里是没有打印语句的等效列表理解。

    from __future__ import print_function 
    comp = [(x,y) for x in [1,2,3] for y in [3,1,4] if x == y] 
    print(comp)

那么有没有办法放入一堆打印语句,以便两个代码打印相同的东西?

使用原始问题的解决方案进行编辑:

使用评论中的方法 - 我已经弄明白了!

所以说你要转换它。

    from __future__ import print_function 

    x = 1
    y = 2
    z = 1
    n = 2

    [[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a + b + c != n]

添加print语句以打印每个循环,显示它是否失败。

    from __future__ import print_function 

    x = 1
    y = 2
    z = 1
    n = 2

    [
        [a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if 
        (print('current loop is',a,b,c) or a + b + c != n)
        and
        (print('condition true at',a,b,c) or True)
    ]

所以真正唯一改变的是最后的条件。

    (a + b + c != n) 

    (print('current loop is',a,b,c) or a + b + c != n)
    and
    (print('condition true at',a,b,c) or True)

其他信息:

因此评论部分中的好东西我认为也可以帮助其他人。我是一个视觉学习者,所以这个网站很棒。

(归功于Tadhg McDonald-Jensen)

3 个答案:

答案 0 :(得分:3)

我认为你不应该在列表推导中运行调试代码,如果你想这样做,你可以将你的代码包装在这样的函数中:

from __future__ import print_function


def foo(x, y):
    print('looping through', x, 'then', y)
    if x == y:
        print('success', x, y)
        return (x, y)

comp = [foo(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x == y]
print(comp)

答案 1 :(得分:2)

您需要评估print函数,但返回值无效,因为它总是None。您可以使用and / or将其与其他表达式合并。

comp = [(x,y) for x in [1,2,3] for y in [3,1,4] if (print('looping through',x,'then',y) or x == y) and (print('success', x, y) or True)]

我真的希望你只是出于教育目的这样做,因为它很难看。仅仅因为可以做某事并不意味着应该

答案 2 :(得分:1)

PEP 202引入了列表理解,其中指出:

  

建议允许条件构造列表文字   使用for和if子句。他们将以相同的方式嵌套循环   如果语句现在嵌套。

列表理解旨在每次迭代仅使用for循环,if条件和.append方法替换形成列表的构造。列表推导中无法使用任何其他结构,因此除非您将打印件粘贴到其中一个允许的组件中,否则无法添加它们。

话虽如此,在有条件的情况下 - 在技术上可行的情况下 - 将印刷声明强烈推荐

[a for a in x if print("this is a bad way to test",a)]