猫猫1 发表于 2015-4-21 11:16:26

python开发_++i,i += 1的区分

  在很多编程语言(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.iyunv.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来实现递增,递减。')
  
页: [1]
查看完整版本: python开发_++i,i += 1的区分