【问题标题】:Python one-liner with input and conditional?带有输入和条件的Python单线?
【发布时间】:2017-05-13 18:14:51
【问题描述】:

有没有办法将三元运算符与输入结合使用,一次性将某些内容分配给变量?

更详细的方式:

# assume this happened a while back.
myVariable = "user: "

# I'd like to get these two lines down to one.
myInputResult = input('Enter something, or just hit Enter for the default: ')
myVariable += "the user typed: " + myInputResult if myInputResult != '' else 'the user did not type anything'

我需要做的是引用 input() 函数中的值,而无需先将其分配给变量。

我在其他语言中看到了一种技术,但是当您将赋值视为变量时,Python 似乎不支持返回赋值:

myVariable += "the user typed " + x if (x = input("Enter something or nothing: ")) != '' else "the user did not type anything"

不起作用。

请注意,即使input 可以返回默认值,这还不够,因为当用户不输入任何内容时,静态文本会有所不同。

变量方法很好,但我只是在寻找一种更简洁的方法来编写代码,如果可能的话。

Python 3,顺便说一句。

【问题讨论】:

  • ...但是你为什么要保存击键?

标签: python


【解决方案1】:

Python 没有内联赋值。您可以编写一个函数,将转换应用于真值并保持空字符串等假值不变(这是Optional.map-type 函数的“精简版”):

def map_true(fn, value):
    return value and fn(value)

并按如下方式使用:

myVariable += (
    map_true("the user typed {}".format, input("Enter something or nothing: ")) or
    "the user did not type anything")

但这并不是一个巨大的进步。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多