【发布时间】: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