>>> s='1234'
>>>
ss=reversed(s)
>>> s
'1234'
>>> ss
>>>
''.join(ss)#第一次
'4321'
>>>
''.join(ss)#第二次为空,原因见本文最后
''
为什么reversed()之后,第二次for循环或第二次list()或第二次tuple()或第二次join()得到的结果为空?我们以第2个例子具体说明一下:
That's because reversed creates an iterator, which is already spent
when you're calling list(ll) for the second time.
The reason is that ll is not the reversed list itself, but a
listreverseiterator. So when you call list(ll) the first time, it
iterates over ll and creates a new list from the items output from
that iterator.When you do it a second time, ll is still the
original iterator and has already gone through all the items, so it
doesn't iterate over anything, resulting in an empty list.
小编来翻译一下:
这是因为反向创建了一个迭代器,该迭代器在第二次调用列表(LL)时已经使用过了。
其原因就是ll不是反转列表本身,而是一个列表反向迭代器。所以当你第一次调用列表(ll),它会遍历ll并且创建一个新的列表从项目输出迭代器。当你再进行一次,ll仍然是原来的迭代器,已经经历了所有的项目,所以它不会再遍历什么,这就造成了空列表。
总结:reversed()之后,只在第一次遍历时返回值。