“只能加入一个可迭代的”python 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32144173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:05:56  来源:igfitidea点击:

"Can only join an iterable" python error

pythonpython-3.xiterable

提问by Derek

I've already looked at this post about iterable python errors:

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

"Can only iterable" Python error

“只能迭代” Python 错误

But that was about the error "cannot assign an iterable". My question is why is python telling me:

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

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

I don't know what I am doing wrong! I was following this thread:

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

Reverse word order of a string with no str.split() allowed

反转字符串的词序,不允许 str.split()

and specifically this answer:

特别是这个答案:

>>> 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'

and adapter the code to make it have an input. But when I ran it, it said the error above. I am a complete novice so could you please tell me what the error message means and how to fix it.

并调整代码以使其具有输入。但是当我运行它时,它说上面的错误。我是一个完整的新手,所以请您告诉我错误消息的含义以及如何修复它。

Code Below:

代码如下:

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)

The program should take an input like apples and pears and then produce an output pears and apples.

该程序应该接受像 apples 和 pears 这样的输入,然后产生一个输出 pears and apples。

Help would be appreciated!

帮助将不胜感激!

采纳答案by Daniel Roseman

splitlist1.reverse(), like many list methods, acts in-place, and therefore returns None. So tobereversedlist1is therefore None, hence the error.

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

You should pass splitlist1directly:

你应该splitlist1直接通过:

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

回答by Eds_k

string join must satisfy the connection object to be iterated(list, tuple)

string join 必须满足要迭代的连接对象(list, tuple)

splitlist1.reverse() returns None, None object not support iteration.

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