Python 如果元素包含特定字符,则从列表或集合中删除该元素

Python 如果元素包含特定字符,则从列表或集合中删除该元素,python,for-loop,iteration,runtime-error,attributeerror,Python,For Loop,Iteration,Runtime Error,Attributeerror,我得到了一个txt文件的月份,我打开并填写到一个列表或设置。我需要遍历列表并删除任何带有字母“r”或“r”的月份。我尝试使用集合和列表来实现这一点,但不断出现运行时错误。以下是我使用集合的代码: monthList = {} def main(): monthList = fillList() print(monthList) removeRMonths(monthList) def fillList(): infile = open("SomeMonths.

我得到了一个txt文件的月份,我打开并填写到一个列表或设置。我需要遍历列表并删除任何带有字母“r”或“r”的月份。我尝试使用集合和列表来实现这一点,但不断出现运行时错误。以下是我使用集合的代码:

monthList = {}

def main():
    monthList = fillList()
    print(monthList)
    removeRMonths(monthList)

def fillList():
    infile = open("SomeMonths.txt")
    monthList = {line.rstrip() for line in infile}
    return monthList

def removeRMonths(monthList):
    for month in monthList:
        for ch in month:
            if ch == "r" or ch == "R":
                monthList.remove(month)
    print(monthList)

main()
我收到的错误是:

Traceback (most recent call last):
  File "/Users/hwang/Desktop/Week7.py", line 115, in <module>
    main()
  File "/Users/hwang/Desktop/Week7.py", line 99, in main
    removeRMonths(monthList)
  File "/Users/hwang/Desktop/Week7.py", line 107, in removeRMonths
    for month in monthList:
RuntimeError: Set changed size during iteration
>>> 
我的错误是:

Traceback (most recent call last):
  File "/Users/hwang/Desktop/Week7.py", line 117, in <module>
    main()
  File "/Users/hwang/Desktop/Week7.py", line 99, in main
    removeRMonths(monthList)
  File "/Users/hwang/Desktop/Week7.py", line 110, in removeRMonths
    monthList.remove(month)
AttributeError: 'generator' object has no attribute 'remove'
回溯(最近一次呼叫最后一次):
文件“/Users/hwang/Desktop/Week7.py”,第117行,在
main()
文件“/Users/hwang/Desktop/Week7.py”,第99行,主
月份(月列表)
文件“/Users/hwang/Desktop/Week7.py”,第110行,以月为单位
月列表。删除(月)
AttributeError:“生成器”对象没有属性“删除”

这些错误的原因是什么?我试着用谷歌搜索每个错误信息,但找不到任何我能理解的答案。我是一个初学者,所以我希望有一个容易理解的答案。提前谢谢

迭代时不应修改listor集

首先使用列表理解创建列表。然后使用另一个列表理解来过滤掉元素。最后,在过滤完成后,使用slice assignment更新原始列表

monthList = ()

def main():
    monthList = fillList()
    print(monthList)
    removeRMonths(monthList)

def fillList():
    infile = open("SomeMonths.txt")
    monthList = [line.rstrip() for line in infile]
    return monthList

def removeRMonths(monthList):
    monthList[:] = [month for month in monthList if 'r' not in month.lower()]
    print(monthList)

在对列表进行迭代时不应修改列表。您的第二个版本没有使用列表。您需要
[line.rstrip()for line in infle]
来创建一个列表。在第一种情况下,当您使用for循环在集合上迭代时,您正在从集合中删除一个元素,这是不允许的。在第二种情况下,它仍然不应该工作,但是您还尝试从生成器对象
()
中删除它,该对象与列表
[]
不同。您可以复制您的monthList/monthSet,并在从副本中删除时迭代原始内容。如果你熟悉这些,理解也会起作用。我不习惯使用列表理解,但现在我明白了。非常感谢。如果你编写Python,你应该习惯它,这是一个很棒的特性。
monthList = ()

def main():
    monthList = fillList()
    print(monthList)
    removeRMonths(monthList)

def fillList():
    infile = open("SomeMonths.txt")
    monthList = [line.rstrip() for line in infile]
    return monthList

def removeRMonths(monthList):
    monthList[:] = [month for month in monthList if 'r' not in month.lower()]
    print(monthList)