为什么Python中没有++和——运算符?


当前回答

首先,Python只是间接地受到C的影响;它深受ABC的影响,ABC显然没有这些操作符,所以在Python中找不到它们也不足为奇。

其次,正如其他人所说,递增和递减已经由+=和-=支持。

第三,对++和——操作符集的完全支持通常包括对它们的前缀和后缀版本的支持。在C和c++中,这可能会导致各种“可爱的”构造,这些构造(对我来说)似乎违背了Python所信奉的简单和直接的精神。

例如,while C语句while(*t++ = *s++);对于一个有经验的程序员来说,它可能看起来简单而优雅,但对于一个初学者来说,它一点也不简单。加上前缀和后缀的增量和减量的混合,甚至许多专业人士也不得不停下来思考一下。

其他回答

因为,在Python中,整数是不可变的(int's +=实际上返回一个不同的对象)。

同样,使用++/——,您需要考虑前后的递增/递减,并且只需要多击一次键就可以写出x+=1。换句话说,它以很少的收益为代价避免了潜在的混乱。

我知道这是一个旧线程,但最常见的用例++ I没有涵盖,即手动索引集时,没有提供索引。这种情况就是python提供enumerate()的原因

示例:在任何给定的语言中,当你使用像foreach这样的构造来遍历一个集合时——为了示例的目的,我们甚至会说它是一个无序的集合,你需要一个唯一的索引来区分它们

i = 0
stuff = {'a': 'b', 'c': 'd', 'e': 'f'}
uniquestuff = {}
for key, val in stuff.items() :
  uniquestuff[key] = '{0}{1}'.format(val, i)
  i += 1

在这种情况下,python提供了一个枚举方法,例如。

for i, (key, val) in enumerate(stuff.items()) :

要完成那一页上已经很好的答案:

让我们假设我们决定这样做,前缀(++i)将打破一元的+和-操作符。

现在,用++或——作为前缀没有任何作用,因为它使一元加运算符两次(没有任何作用)或一元减运算符两次(两次:取消自身)

>>> i=12
>>> ++i
12
>>> --i
12

所以这可能会打破这个逻辑。

现在,如果需要它来进行列表推导或lambdas,从python 3.8开始,可以使用新的:=赋值操作符(PEP572)

预递增a并赋值给b:

>>> a = 1
>>> b = (a:=a+1)
>>> b
2
>>> a
2

后增量只需要通过减1来弥补过早的加法:

>>> a = 1
>>> b = (a:=a+1)-1
>>> b
1
>>> a
2

Maybe a better question would be to ask why do these operators exist in C. K&R calls increment and decrement operators 'unusual' (Section 2.8page 46). The Introduction calls them 'more concise and often more efficient'. I suspect that the fact that these operations always come up in pointer manipulation also has played a part in their introduction. In Python it has been probably decided that it made no sense to try to optimise increments (in fact I just did a test in C, and it seems that the gcc-generated assembly uses addl instead of incl in both cases) and there is no pointer arithmetic; so it would have been just One More Way to Do It and we know Python loathes that.

我相信这源于Python的信条“显式优于隐式”。