为什么str(reversed(...))没有给我反向字符串? [英] Why str(reversed(...)) doesn't give me the reversed string?
问题描述
我正试图习惯于迭代器.为什么输入
I'm trying to get used to iterators. Why if I type
b = list(reversed([1,2,3,4,5]))
它将给我一个反向列表,但是
It will give me a reversed list, but
c = str(reversed('abcde'))
不会给我一个颠倒的字符串吗?
won't give me a reversed string?
推荐答案
在Python中, reversed
实际上返回一个反向迭代器.因此,应用于迭代器的 list
会为您提供列出对象.
In Python, reversed
actually returns a reverse iterator. So, list
applied on the iterator will give you the list object.
在第一种情况下,输入也是一个列表,因此将list
的结果应用于reversed
迭代器似乎对您来说合适.
In the first case, input was also a list, so the result of list
applied on the reversed
iterator seemed appropriate to you.
在第二种情况下, str
应用于返回的迭代器对象实际上将为您提供它的字符串表示形式.
In the second case, str
applied on the returned iterator object will actually give you the string representation of it.
Instead, you need to iterate the values in the iterator and join them all with str.join
function, like this
>>> ''.join(reversed('abcde'))
edcba
这篇关于为什么str(reversed(...))没有给我反向字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!