python灵活,内联变量赋值

bum*_*kin 2 python

我想灵活地为python中的变量赋值,无论我的代码在哪里变量.

例如,给定If语句中的变量x ...

if(x == 5):
    print "that's odd."
else:
    print "Woot."
Run Code Online (Sandbox Code Playgroud)

我希望能够像这样在if语句中分配x:

if((x=3) == 5):
    print "that's odd."
else:
    print "Woot."
Run Code Online (Sandbox Code Playgroud)

那可能吗?这是另一个例子.假设我有一条线:

y = x + 10
Run Code Online (Sandbox Code Playgroud)

我想在那里分配x:

y = (x=3) + 10
Run Code Online (Sandbox Code Playgroud)

所以我正在寻找一种方法在我的代码中的任何地方找到一个变量并给它赋值.是否有pythonic语法?

osg*_*sgu 6

"在Python中,赋值是一个语句,而不是一个表达式,因此不能在任意表达式中使用.这意味着常见的C语言如下:

while (line = readline(file)) {
    ...do something with line...
}
Run Code Online (Sandbox Code Playgroud)

要么

if (match = search(target)) {
    ...do something with match...
}
Run Code Online (Sandbox Code Playgroud)

不能在Python中使用."

http://effbot.org/pyfaq/why-can-ti-use-an-assignment-in-an-expression.htm


K3-*_*rnc 6

在Python 3.8中,可以使用赋值表达式(operator :=):

if (x := 3) == 5:
    print("that's odd")

y = (x := 3) + 10
Run Code Online (Sandbox Code Playgroud)