python - 如果条件为 False,则重新启动循环并编辑原始列表

标签 python for-loop while-loop

我正在对 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)

一些问题:

  1. 我无法检查 results 的值对于每个 jresults[i]开始进入我的真实代码是一个模型类,它针对 results[i] 中的所有元素完成。同时(这就是示例中使用双 for 循环的原因)。

  2. 我认为代码对于这个简单的示例来说是有效的,但对于更大的列表和更复杂的计算来说可能会很耗时。例如,如果我将列表更改为 a = [[9,8,7], [6,5,3,2,4]]我必须包含更多 for 循环。

  3. 我可以使用类似 range(restart, len(a)) 的东西在第二个for i循环,但第 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环形?我可以从i=0重新开始计算如果没有其他方法并且我不必包含更多 for循环以获得包含更多元素的更大列表。

最佳答案

您已重复该代码两次。

如果您想将值 1 赋给变量 i 并“重新启动”,则使用 while 循环会更好。例如:

while i <= len(a):

       # your code
       # restar i value when you need it using:
       i = 1;

我不知道你什么时候想重新启动 i 的值,但你可以在 continue 子句之前在 else 中尝试一下。

i = 1

关于python - 如果条件为 False,则重新启动循环并编辑原始列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55955008/

相关文章:

python - 返回Python的for循环

python,索引错误

javascript - 循环根据长度精确迭代,但每次迭代插入相同的记录

php - mysql_fetch_assoc() 仅适用于 WHILE 循环中的一次迭代

c++ - 用 while 循环替换 for 循环时我做错了什么?

python - 如何在 Django 中停止自动大写 verbose_name

java - 如何定义嵌套类常量?

python - Django 迁移 django.db.utils.OperationalError : no such table:

python - (flask) python - mysql - 在带有来自 URL 的变量的选择查询中使用 where 子句

c - 与 ">"比较时,while 循环条件从不评估为真