反復可能な Python エラーに関するこの投稿をすでに確認しました:
しかし、それは「反復可能オブジェクトを割り当てることができません」というエラーに関するものでした。私の質問は、なぜ Python が私に次のように言うのかということです。
"list.py", line 6, in <module>
reversedlist = ' '.join(toberlist1)
TypeError: can only join an iterable
何が間違っているのか分かりません! 私はこのスレッドをフォローしていました:
具体的にはこの答えです:
>>> s = 'This is a string to try'
>>> r = s.split(' ')
['This', 'is', 'a', 'string', 'to', 'try']
>>> r.reverse()
>>> r
['try', 'to', 'string', 'a', 'is', 'This']
>>> result = ' '.join(r)
>>> result
'try to string a is This'
コードをアダプターして入力を作成します。しかし、実行すると、上記のエラーが表示されました。私は完全な初心者なので、エラー メッセージの意味と修正方法を教えてください。
以下のコード:
import re
list1 = input ("please enter the list you want to print")
print ("Your List: ", list1)
splitlist1 = list1.split(' ')
tobereversedlist1 = splitlist1.reverse()
reversedlist = ' '.join(tobereversedlist1)
yesno = input ("Press 1 for original list or 2 for reversed list")
yesnoraw = int(yesno)
if yesnoraw == 1:
print (list1)
else:
print (reversedlist)
プログラムは、apples や pears などの入力を受け取り、pears と apples という出力を生成する必要があります。
ご協力いただければ幸いです!
ベストアンサー1
splitlist1.reverse()
は、多くのリスト メソッドと同様に、インプレースで動作し、 を返しますNone
。したがってtobereversedlist1
は None であり、エラーが発生します。
直接渡す必要がありますsplitlist1
:
splitlist1.reverse()
reversedlist = ' '.join(splitlist1)