为什么使用print(iterable)时输出不打印?

2024-05-01 21:53:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白为什么在第1种情况下不打印输出,而在第二种情况下,在使用list之后,它工作了。你知道吗

案例一:

s='india'

print(reversed(s))

输出

<reversed object at 0x...>

案例二:

s='india'

print(list(reversed(s)))

输出

['a', 'i', 'd', 'n', 'i']

Tags: object情况at案例listprintindia打印输出
2条回答

如果要反转字符串,请尝试以下操作:

string = ''.join(reversed(s))

这是因为reversed输出一个迭代器,迭代器不保存值,而是动态计算值。“”连接部分使用生成器并生成字符串。你知道吗

有关生成器/迭代器的详细信息,请参见here。你知道吗

从Python文档中:

reversed(seq)

Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).

list([iterable])

The constructor builds a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, [].

所以:

reversed(string)将返回一个遍历字符串的迭代器。list(iterator)将迭代器转换为一个列表。list(string)将字符串拆分为其组成字符。你知道吗

因此

list('india')返回['i', 'n', 'd', 'i', 'a']

reversed('india')返回<reversed object at 0x1090b48d0>,这是一个迭代器

可以使用list运算符将迭代器转换为列表:

list(reversed('india'))返回['a', 'i', 'd', 'n', 'i']

或者你可以迭代:

for n in reversed('india'):
   print(n)

打印出来的

a
i
d
n
i

相关问题 更多 >