for之Python vs C#

 1 class test(object):
 2     def rangetest(self):
 3         for i in range(2,0,-1):
 4             print i
 5         print i
 6         i=2
 7         while i>0:
 8             print i
 9             i=i-1;
10         print i

如上这段代码,输出结果分别为

for(2   1)  

while(2  1)

0

这是很显而易见的结果。但是我在应用中却将两者混淆,导致程序运行失败。

如下是一个插入算法

 1 class Insertion(OrderStrategy):
 2     def Sort(self,args):
 3         args = list(args)
 4         length = len(args)
 5         for i in range(1,length):
 6             temp = args[i]
 7             #for j in range(i,-1,-1):#range don't contain the stop element so the middl -1 means stop at 0
 8             #    if args[j - 1] > temp: #here should check j>0 though no error occurs
 9             #        args[j] = args[j - 1]
10             #    else:
11             #        break
12             j=i;
13             while j>0:
14                 if args[j - 1] > temp:
15                     args[j] = args[j - 1]
16                     j=j-1;
17                 else:
18                     break
19             args[j] = temp #asignment the current (position i) element to j(the first element less than it on the left side of i)
20         
21         print "Insertion:"
22         print args
23         return args

使用第7至11行的代码时替代不了第12到18行的代码的。

c#中

for (var i = 0; i < 10; i++) { }

他是会有边界检测,i会自增到10,比较结果为false,则结束

而Python的for只是用来遍历元素,并没有比较条件可以让他提前结束。当然你可以在遍历中自己加入break强行进行退出遍历,如下

            for j in range(i,-1,-1):#range don't contain the stop element so the middl -1 means stop at 0
                if args[j - 1] > temp and j>0:
                    args[j] = args[j - 1]
                else:
                    break

这段代码与上边12-18行一个效果。(但是恐怕没人会这么用吧~~~毕竟人家Python本来就支持负索引)

是自己的语法误使用造成错误,仅作记录提醒自己。

原文地址:https://www.cnblogs.com/cotton/p/3919997.html