“只能加入可迭代”Python 错误

问题描述 投票:0回答:4

我已经看过这篇关于可迭代Python错误的文章:

“只能迭代”Python 错误

但这与错误“无法分配可迭代”有关。我的问题是为什么 python 告诉我:

 "list.py", line 6, in <module>
    reversedlist = ' '.join(toberlist1)
TypeError: can only join an iterable

我不知道我做错了什么!我正在关注这个帖子:

在不允许 str.split() 的情况下反转字符串的词序

特别是这个答案:

>>> 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
4个回答
29
投票

splitlist1.reverse()
,与许多列表方法一样,就地起作用,因此返回
None
。因此
tobereversedlist1
为 None,因此出现错误。

您应该直接通过

splitlist1
:

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

1
投票

字符串连接必须满足要迭代的连接对象(列表、元组)

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


0
投票
def mostActive(customers):
    total = len(customers)
    dict_ = {}
    for i in customers:
        dict_[i] = dict_.get(i, 0) + 1
    res = {}
    for i in dict_:
        res[i] = (dict_[i]/total)*100
    print(res)
    traders = []
    for i in res:
        if res[i] >= float(5):
            traders.append(i)
    return (sorted(traders))

0
投票

文件“main.py”,第 16 行,位于 pass_word=“”.join(代码) 类型错误:只能连接一个可迭代对象  告诉我为什么

© www.soinside.com 2019 - 2024. All rights reserved.