2013-10-14 36 views
1

正如你應該知道,在Python中,下面是一個有效的循環在Python:在Python中創建一個「實際」for循環?

animals = [ 'dog', 'cat', 'horse' ] # Could also be a dictionary, tuple, etc 

for animal in animals: 
    print animal + " is an animal!" 

這通常是罰款。但對我來說,我希望做一個像你會在C/C++/Java的等的for循環看起來像這樣的方式循環:

for (int x = 0; x <= 10; x++) { 
    print x 
} 

我怎麼能做到在Python這樣的事情?我將不得不建立這樣的事情,還是有可以做到這一點,我缺少的(我GOOGLE了好幾個星期)的實際方式:

i = 0 

while i is not 10: 
    print i 

還是有怎樣一個標準去做這個?我發現以上並不總是有效。是的,對於上述情況我可以這樣做:

for i in range(10): 
    print i 

但在我的情況下,我不能這樣做。

+4

爲什麼你能不能做到'我在範圍內(10)'? – Mike

+0

我正在做蛇,我需要循環整個網格。我無法使用此範圍。 – Eamonn

+0

'爲我在範圍(grid.width)'? – Schleis

回答

9

爲什麼你需要一個C風格的索引跟蹤循環?我可以想象幾個例子。

# Printing an index 
for index, name in enumerate(['cat', 'dog', 'horse']): 
    print "Animal #%d is %s" % (index, name) 

# Accessing things by index for some reason 
animals = ['cat', 'dog', 'horse'] 
for index in range(len(animals)): 
    previous = "Nothing" if index == 0 else animals[index - 1] 
    print "%s goes before %s" % (previous, animals[index]) 

# Filtering by index for some contrived reason 
for index, name in enumerate(['cat', 'dog', 'horse']): 
    if index == 13: 
    print "I am not telling you about the unlucky animal" 
    continue # see, just like C 
    print "Animal #%d is %s" % (index, name) 

如果你一意孤行,模擬反跟蹤環,你已經有了一個圖靈完備的語言,這是可以做到:

# ...but why? 
counter = 0 
while counter < upper_bound: 
    # do stuff 
    counter += 1 

如果你覺得有必要在循環中重新分配循環計數器變量,機會很高,你做錯了,無論是C循環還是Python循環。

+0

嗯,也許我做錯了。以下是我需要在Java中執行的操作: 'for(int x = BOX_WIDTH; x Eamonn

+0

@Eamonn:這很容易完成,因爲'範圍內的x(BOX_WIDTH ,GRID_WIDTH * BOX_WIDTH):...#do stuff'。這些東西將爲'x'的每個值完成,使得'BOX_WIDTH'≤'x' <'GRID_WIDTH * BOX_WIDTH'。 – 9000

9

我想從你的評論,你試圖循​​環網格索引。這裏有一些方法:

平原簡單的雙for循環:

for i in xrange(width): 
    for j in xrange(height): 
     blah 

使用itertools.product

for i, j in itertools.product(xrange(width), xrange(height)): 
    blah 

使用numpy的,如果你能

x, y = numpy.meshgrid(width, height) 
for i, j in itertools.izip(x.reshape(width * height), y.reshape(width * height): 
    blah 
+0

......並且不要忘記'枚舉' – user4815162342