【问题标题】:Change in for-loop range by deleting a list element通过删除列表元素更改 for 循环范围
【发布时间】:2016-07-08 13:32:48
【问题描述】:

我是 python 和一般编程的新手,目前正在学习基础知识。在下面的脚本中,我试图检查每个列表元素中的字母数量并删除包含五个或更多字母的字母。我正在使用 for 循环来实现这一点,但由于列表元素数量的变化与最初考虑的 for 循环范围不对应,因此出现了问题。我试图让范围自行变化,但仍然出现错误。

# -*- coding: utf-8 -*-

magicians =['alice','david','carolina']

def counter(word):
    x= sum (c != ' ' for c in word)
    return x

print magicians
for i in range (0,3):
        magicians[i]=magicians[i].title()
print magicians
q=
Y=range (0,q)

for i in Y:
    x= counter(magicians[i])
    print x    
    if x<=5:
        print 'this component will be deleted:', magicians[i]
        del magicians[i]
        q=q-1
        Y=range (0,q)
print magicians

谢谢

【问题讨论】:

    标签: python string for-loop string-length del


    【解决方案1】:

    您的代码的主要问题是循环中的Y = ... 不会for i in Y 中的Y 产生影响。

    for i in Y:
        ...
            Y=range (0,q)
    

    可以更改代码以使用while 循环,并手动管理当前索引和最大索引,但这很容易出错:

    i = 0
    while i < q:
        x= counter(magicians[i])
        if x<=5:
            print 'this component will be deleted:', magicians[i]
            del magicians[i]
            q=q-1
        else:
            i += 1
    

    与其在迭代同一个列表时从列表中删除元素,不如填充一个 second 列表,只保存您想要保留的元素,例如使用列表推导:

    good_magicians = [m for m in magicians if counter(m) > 5]
    

    【讨论】:

      【解决方案2】:

      这篇文章对您的问题有一个复杂的答案:Remove items from a list while iterating

      最简单的方法是创建一个仅包含您真正想要的元素的新列表。

      【讨论】:

      • 为什么我的回答被否决了?请说明原因。
      • 感谢您的回答。我实际上投了赞成票,但出现的是 (-1)。
      猜你喜欢
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多