【问题标题】:Python: Is it possible to judge input using if statement in one linePython:是否可以在一行中使用if语句判断输入
【发布时间】:2018-01-17 14:55:03
【问题描述】:

我正在使用 python 3.6。我想输入一个字符串或其他东西,并通过一行中的 if 语句来判断它。 这可能是一个简单的问题,但我无法解决这个问题。我知道如何在没有一行的情况下做:

words = input()
if words == 'a':
    print(words)
else:
    print('Not a')

但是,我不能把它放在一行中。我想做的是这样的:

print(input() if input() == 'a' else 'Not a')

它不起作用。第一个输入和第二个输入是不同的。是否可以保留第一次输入的结果并在一行中检查其条件? 谢谢!

【问题讨论】:

    标签: python python-3.x syntax


    【解决方案1】:

    您可以使用单例生成器/列表技巧来避免调用函数两次,但仍会重用其结果:

    print(next(x if x == 'a' else 'Not a' for x in [input()]))
    

    当您使用它时,您还可以缩短三元 x if y else z 构造以变得更加神秘 :-)

    print(next(('Not a', x)[x == 'a'] for x in [input()]))
    

    但更少的行本身并不是目的。您拥有的五行代码完全有效且可读

    【讨论】:

    • OP 注意:请特别注意最后一行 => 较少的行本身并不是目的。您拥有的五行是完全有效且可读的 - 怎么强调都不过分。
    • 谢谢,我会仔细记住这一点:)。我只是对一条线的工作原理感兴趣。这完美地回答了我的问题。
    【解决方案2】:
    >>> words = input()
    'a'
    >>> print(words if words=='a' else 'not a')
    a
    >>> words = input()
    'b'
    >>> print(words if words=='a' else 'not a')
    not a
    

    【讨论】:

    • "是否可以保留第一次输入的结果并检查其条件一行?"
    • 啊,是的,没注意到
    猜你喜欢
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 2021-05-13
    相关资源
    最近更新 更多