0

我是 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

谢谢

4

2 回答 2

0

您的代码的主要问题是Y = ...inside 循环对in没有影响。Yfor i in 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

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

good_magicians = [m for m in magicians if counter(m) > 5]
于 2016-07-08T13:45:36.440 回答
-1

这篇文章中对您的问题有一个复杂的答案:在迭代时从列表中删除项目

最简单的方法是创建一个仅包含您实际需要的元素的新列表。

于 2016-07-08T13:35:31.560 回答