アンディ・ホワン:
私は私がリストまたはセットに開き、塗りつぶしヶ月の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'
これらのエラーの原因は何ですか?私は、それぞれのエラーメッセージをグーグルで試してみましたが、私は、私が理解できる任意の答えを見つけることができませんでした。私は容易に理解できる答えをいただければ幸いですので、私は初心者です。前もって感謝します!
Barmar:
あなたはそれを反復処理している間は、listorセットを変更しないでください。
最初の場所でリストを作成し、リスト内包表記を使用してください。その後要素をフィルタリングするために別のリスト内包表記を使用しています。最後に、フィルタリングが行われた後、所定の位置に元のリストを更新するために、スライスの割り当てを使用しています。
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)