gpt4 book ai didi

Python for 循环问题

转载 作者:行者123 更新时间:2023-11-28 20:25:16 25 4
gpt4 key购买 nike

我在 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
}
}

在 python 中似乎不可能减去索引:

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

最佳答案

编辑:根据您发布的算法,进行一些清理

p, v = [[vtx.pop(0)]],[[vec.pop(0)]]
while len( vtx ):
x = vtx.pop( 0 )
b = vec.pop( 0 )
a = v[ -1 ][ 0 ]
if threshold >= math.sqrt((a[0] - b[0])**2 + (a[1]- b[1])**2 + (a[2]- b[2])**2):
v[ -1 ].append( b )
p[ -1 ].append( x )
else:
v.append( [ b ] )
p.append( [ x ] )

不知道是什么

我不确定原始 PHP 代码是否也能正常工作。或者它可能,但只是偶然而且肯定不是有效的。我假设您想遍历列表,删除与特定值匹配的项目。您似乎已经意识到这样做的一个基本问题是您正在修改您试图迭代的列表。这在 Python 中非常简单:

for c in verts[:]:
if remove_condition(c):
verts.remove(c)

在这里,您正在制作 verts 列表的副本以通过 [:] 进行迭代每次迭代都使用 c,它是对 verts -copy- 中项目的引用。然后,您使用值 c 在原始列表上调用 remove(),这将删除它遇到的值 c 的第一个实例。

显然,在涉及字典等的不同情况下,这里有很多细微差别,但这应该让您入门。

Python 教程通常是很好的资源http://docs.python.org/2/reference/compound_stmts.html#for

关于Python for 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15450980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com