0

Python 有 +=、-=、*=、%= 等。这有通用形式吗?我想尝试的第一件事是:

x = _ + 1

作为x+=1. 我对此很好奇,因为我的实际代码现在看起来像这样:

a = x[y][z]
x[y][z] = f(a)

并且在我的脑海中有些东西是x[y][z] = f( _ )有道理的,也许它只是我想在那里,但不是。Python中有类似的东西吗?

4

2 回答 2

3

不,没有,对不起。我自己也曾多次希望得到类似的东西。

于 2013-07-11T18:26:25.873 回答
1

所以你可以这样做,有点。虽然这是一个肮脏的黑客...

import inspect, sys

def getVariableAtBeginningOfLine():
    lineNumber = inspect.currentframe().f_back.f_lineno
    with open(sys.argv[0]) as f:
        lines = f.read().split("\n")

    #now we have the line we call the function on. 
    line = lines[lineNumber-1]

    #do whatever we want with the line, in this case take the variable at the beginning of the line.
    return eval(line.split()[0])

x = 10

print x #10

x = getVariableAtBeginningOfLine() + 1

print x #11
于 2013-07-11T19:38:09.743 回答