带输入和条件的Python oneliner?

2024-09-28 19:34:50 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以将三元运算符与输入结合使用,在一次操作中为变量赋值?你知道吗

更详细的方式:

# 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可以返回默认值,但这还不够,因为当用户不输入任何内容时,静态文本会有所不同。你知道吗

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

顺便说一句,Python 3


Tags: ortheto方法inputifelsesomething
1条回答
网友
1楼 · 发布于 2024-09-28 19:34:50

Python没有内联赋值。您可以编写一个函数,将转换应用于truthy值,并保持falsy值(如空字符串)不变(这是Optional.map类型函数的“lite”版本):

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")

但这并不是一个巨大的进步。你知道吗

相关问题 更多 >