【问题标题】:"Can only join an iterable" python error“只能加入一个可迭代的”python 错误
【发布时间】:2015-11-15 15:01:30
【问题描述】:

我已经看过这篇关于可迭代 python 错误的帖子:

"Can only iterable" Python error

但那是关于“无法分配可迭代”的错误。我的问题是为什么 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)

程序应该接受像苹果和梨这样的输入,然后产生一个输出梨和苹果。

我们将不胜感激!

【问题讨论】:

    标签: python python-3.x iterable


    【解决方案1】:

    splitlist1.reverse(),像许多列表方法一样,就地执行,因此返回None。所以tobereversedlist1 是 None,因此是错误。

    你应该直接传递splitlist1

    splitlist1.reverse()
    reversedlist = ' '.join(splitlist1)
    

    【讨论】:

    • 您将如何使程序反向列表包含逗号?像苹果,梨去梨,苹果
    • 将逗号而不是空格传递给split
    • 如何同时进行空格分割和逗号分割?这样无论代码如何,您都可以同时输入 apples、pear 和 apples pears。
    • 有几种方法,但可能最简单的方法是先用逗号替换空格,然后用逗号分隔:splitlist1 = list1.replace(' ', ',').split(',')
    【解决方案2】:

    字符串连接必须满足要迭代的连接对象(list, tuple)

    splitlist1.reverse() 返回None,None对象不支持迭代。

    【讨论】:

      猜你喜欢
      • 2018-01-03
      • 2022-01-26
      • 1970-01-01
      • 2013-11-18
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 2016-11-24
      相关资源
      最近更新 更多