【发布时间】:2019-05-02 14:49:34
【问题描述】:
我正在使用for 循环对列表进行一些操作,当不满足if 条件时,我需要删除该列表的元素,然后再次执行操作。
我见过calculator(和here)示例,他们使用while 循环,但我无法适应我的问题。
这是我想做的一个例子
a = [[9,8,7], [6,5,3,4]] # different length sublists, elements are not repeated
results = [[] for i in range(len(a))]
for i in range(len(a)):
for j in range(len(a[i])):
results[i].append(a[i][j]/4)
# see below for explanation for this step
for j in range(len(a[i])):
if results[i][j] <1:
del a[i][j]
print('element',j,'removed from sublist',i)
break
else:
continue
# when there is an element that doesn't met the condition I want to remove
# that element and restart the calculation for that step, in this case i=1
# but this depends on the list
# The calculation is then done for the list with the element removed
# this is way I'm repeating the code below (which I want to avoid)
results = [[] for i in range(len(a))]
for i in range(len(a)):
for j in range(len(a[i])):
results[i].append(a[i][j]/4)
for j in range(len(a[i])):
if results[i][j] <1:
del a[i][j]
print('element',j,'removed from sublist',i)
break
else:
continue
print(results)
一些问题:
我无法在我的真实代码中检查每个
j步骤的results的值,因为results[i]是一个模型类,它同时针对results[i]中的所有元素完成(这就是为什么示例中的双 for 循环)。我认为代码在这个简单示例中可以正常工作,但对于更大的列表和更复杂的计算可能会很耗时。例如,如果我将列表更改为
a = [[9,8,7], [6,5,3,2,4]],则必须包含更多 for 循环。我可以在第二个
for i循环中使用类似range(restart, len(a))的东西,但是第 2 点的问题仍然存在,它会将新结果附加到旧结果中,例如results = [[2.25, 2.0, 1.75], [1.5, 1.25, 0.75, 1.0, 1.5, 1.25, 1.0]]而不是results = [[2.25, 2.0, 1.75], [1.5, 1.25, 1.0]]。
有没有更好的方法来做到这一点?也许有while 循环?如果没有其他方法并且我不必为具有更多元素的更大列表包含更多 for 循环,我可以从 i=0 重新开始计算。
【问题讨论】:
-
你为什么两次发布相同的代码?
-
@Sheldore 你的意思是在附加结果之前检查
a[i][j]/4<1?问题中对此进行了解释,我无法直接在实际代码中检查这一点,因为results是将模型拟合到数据集的结果。关于您的第二条评论,这是我的问题的一部分,当我第一次生成一个元素已被删除的新列表时,我必须再次为新列表进行计算。
标签: python for-loop while-loop