我遇到了在python中複製for循環的問題。Python for循環問題
這是我的c風格的腳本,只有for循環方面。
for ($c=0 ; $c<size($verts); $c++)
{
//// do some code here
$verts = remove($verts[c],$verts); /// remove this item from the $verts list
$c-=1; /// lower the index becuase an item was removed
for ($n=0 ; $n<size($verts); $n++)
{
if($condition)
$verts = remove($verts[$n],$verts); /// remove this item from the $verts list
$n-=1; /// lower the index becuase an item was removed
}
}
在蟒蛇有它似乎並不纔有可能減去指數:
item = range(10);
for i in item :
del item[i]
i-=1 # this doesn't do anything for the next interation
什麼是用Python語言編寫上面的C循環的最佳方式?
編輯: 這裏是循環的工作,因爲我需要在Python
count = range(len(vtx))
for num in count:
if len(vtx) != 0:
p.append ([]); p[len(p)-1].append(vtx[0])
v.append ([]); v[len(p)-1].append(vec[0])
a = vec[0]
del vtx[0]
del vec[0]
count2 = range(len(vtx))
n2 = 0;
for num2 in count2:
b = vec[n2]
distance = math.sqrt((a[0] - b[0])**2 + (a[1]- b[1])**2 + (a[2]- b[2])**2);
if distance <= threshold :
p[len(p)-1].append (vtx[n2])
v[len(p)-1].append (vec[n2])
vtx.remove(vtx[n2])
vec.remove(vec[n2])
else:
n2+=1
感謝所有的答案。我最終做了一些不太pythonic的事情,因爲我仍然對索引有很多麻煩,並且意識到我可以簡化我的c代碼。 (請參閱帶有工作代碼的更新問題)但是所有的答案都很有幫助,現在我明白了python的工作原理。 – fghajhe 2013-03-16 19:40:46
@fghajhe我發佈了一個基於你的編輯的版本,這個版本更容易遵循。不確定它是否相關,但你的算法是依賴於順序的。如果你重新排列你的vtx/vec對,你會得到不同的結果。 – 2013-03-17 00:03:49