"Can only join an iterable" python 错误
"Can only join an iterable" python error
我已经看过这个 post 关于可迭代的 python 错误:
"Can only iterable" Python error
但那是关于错误 "cannot assign an iterable" 的。我的问题是为什么 python 告诉我:
"list.py", line 6, in <module>
reversedlist = ' '.join(toberlist1)
TypeError: can only join an iterable
我不知道我做错了什么!我在关注这个话题:
Reverse word order of a string with no str.split() allowed
特别是这个答案:
>>> 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)
该程序应采用苹果和梨之类的输入,然后生成梨和苹果之类的输出。
不胜感激!
splitlist1.reverse()
,与许多列表方法一样,就地执行,因此 returns None
。所以 tobereversedlist1
因此是 None,因此是错误。
你应该直接通过splitlist1
:
splitlist1.reverse()
reversedlist = ' '.join(splitlist1)
string join必须满足要迭代的connection对象(list, tuple)
splitlist1.reverse() returns None, None 对象不支持迭代。
我已经看过这个 post 关于可迭代的 python 错误:
"Can only iterable" Python error
但那是关于错误 "cannot assign an iterable" 的。我的问题是为什么 python 告诉我:
"list.py", line 6, in <module>
reversedlist = ' '.join(toberlist1)
TypeError: can only join an iterable
我不知道我做错了什么!我在关注这个话题:
Reverse word order of a string with no str.split() allowed
特别是这个答案:
>>> 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)
该程序应采用苹果和梨之类的输入,然后生成梨和苹果之类的输出。
不胜感激!
splitlist1.reverse()
,与许多列表方法一样,就地执行,因此 returns None
。所以 tobereversedlist1
因此是 None,因此是错误。
你应该直接通过splitlist1
:
splitlist1.reverse()
reversedlist = ' '.join(splitlist1)
string join必须满足要迭代的connection对象(list, tuple)
splitlist1.reverse() returns None, None 对象不支持迭代。