在很多編程語言(C/C++,Java等)中我們都會碰到這樣的語法:
1 int i = 0; 2 ++ i; // -- i;
這樣的語法在上述編程語言中可以實現自增(減),在python中也支持這樣的語法,不過在python中
這樣的用法不是用來自增(減),而是實現數學中的符號運算操作:
1 i = 2 2 ++ i #輸出:2 3 +(+i) #輸出:2 4 -(+i) #輸出:-2 5 +(-i) #輸出:-2 6 -(-i) #輸出:2
在python中,如果要實現自增(減),應該這樣做:
1 i = 2 2 i += 1 #實現自增 3 print(i) #輸出:3 4 i -= 1 #實現自減 5 print(i) #輸出:2
下面看看我做的demo,我想你就會明白
運行效果:
=============================================================
代碼部分:
=============================================================
1 #python ++i,-+i,+-i.--i 2 3 #Author : Hongten 4 #Mailto : hongtenzone@foxmail.com 5 #Blog : http://www.cnblogs.com/hongten 6 #QQ : 648719819 7 #Version : 1.0 8 #Create : 2013-08-30 9 10 #初始化所需列表 11 testA = [] 12 testB = [] 13 testC = [] 14 testD = [] 15 testE = [] 16 testF = [] 17 testG = [] 18 testH = [] 19 20 for a in range(-5, 5, 1): 21 testA.append(++(a)) #++a 22 testB.append(-+(a)) #-+a 23 testC.append(+-(a)) #+-a 24 testD.append(--(a)) #--a 25 testE.append(+(+(a))) #+(+a) 26 testF.append(-(+(a))) #-(+a) 27 testG.append(+(-(a))) #+(-a) 28 testH.append(-(-(a))) #-(-a) 29 30 print('++i : {}'.format(testA)) 31 print('+(+i) : {}'.format(testE)) 32 print('可以看出:++i和+(+i)輸出結果是一樣的,說明他們是等效的\n') 33 print('-+i : {}'.format(testB)) 34 print('-(+i) : {}'.format(testF)) 35 print('可以看出:-+i和-(+i)輸出結果是一樣的,說明他們是等效的\n') 36 print('+-i : {}'.format(testC)) 37 print('+(-i) : {}'.format(testG)) 38 print('可以看出:+-i和+(-i)輸出結果是一樣的,說明他們是等效的\n') 39 print('--i : {}'.format(testD)) 40 print('-(-i) : {}'.format(testH)) 41 print('可以看出:--i和-(-i)輸出結果是一樣的,說明他們是等效的\n') 42 43 test_plus = [] 44 test_sub = [] 45 46 #使用b += 1實現自增 47 for b in range(-5, 5, 1): 48 b += 1 49 test_plus.append(b) 50 51 #使用c -= 1實現自減 52 for c in range(-5, 5, 1): 53 c -= 1 54 test_sub.append(c) 55 56 print('#' * 50) 57 print('i += 1 : {}'.format(test_plus)) 58 print('i -= 1 : {}'.format(test_sub)) 59 print('我們可以使用:i += 1, i -= 1來實現遞增,遞減。')
========================================================
More reading,and english is important.
I'm Hongten
大哥哥大姐姐,覺得有用打賞點哦!多多少少沒關系,一分也是對我的支持和鼓勵。謝謝。
Hongten博客排名在100名以內。粉絲過千。
Hongten出品,必是精品。
E | hongtenzone@foxmail.com B | http://www.cnblogs.com/hongten
========================================================