【问题标题】:Remove element from list or set if it contains certain character如果元素包含特定字符,则从列表或集合中删除元素
【发布时间】:2020-06-17 14:39:51
【问题描述】:

我收到了一个包含月份的 txt 文件,我打开并填写到一个列表或集合中。我需要遍历列表并删除任何带有字母“r”或“R”的月份。我尝试使用集合和列表,但不断收到 RuntimeError。这是我使用集合的代码:

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

这是我尝试使用列表的代码:

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)
            else:
                continue
    print(monthList)

main()

我的错误是:

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'

这些错误的原因是什么?我尝试用谷歌搜索每条错误消息,但找不到任何我能理解的答案。我是初学者,所以我会很感激一个容易理解的答案。提前致谢!

【问题讨论】:

  • 您不应该在迭代列表时修改它。
  • 您的第二个版本没有使用列表。您需要[line.rstrip() for line in infile] 才能列出清单。
  • 在第一种情况下,您在使用 for 循环对其进行迭代时从集合中删除一个元素,这是不允许的。在第二种情况下,它仍然不应该工作,但您还尝试从生成器对象() 中删除,这与列表[] 不同。您可以制作您的monthList/monthSet 的副本,并在从副本中删除时迭代原始文件。如果您熟悉这些,理解也将起作用。

标签: python for-loop iteration runtime-error attributeerror


【解决方案1】:

您不应该在迭代时修改列表集。

首先使用列表推导式来创建列表。然后使用另一个列表推导过滤掉元素。最后,在过滤完成后使用切片分配更新原列表。

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)

【讨论】:

  • 我不习惯使用列表推导,但现在我明白了。谢谢!
  • 如果你编程 Python,你应该习惯它,这是一个很棒的特性。
猜你喜欢
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 2011-03-25
  • 2014-11-08
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
相关资源
最近更新 更多