反转字符串程序的示例背后发生了什么?

huangapple go评论59阅读模式
英文:

what happens behind an example of a reverse string program?

问题

我朋友让我通过反转字符串来改变它,显然反转字符串只会给你对象ID,我设法找到了一种方法来做到这一点,但我不理解代码下面发生了什么。我不明白的部分是join()如何与一个反转后的值一起工作,当反转后的值会在使用join()之前转换成列表或元组吗?我没有明确要将字符串更改为列表,那么代码的哪一部分执行了这种更改?

a = 'apple'
b = '1'.join(reversed(a))
print(b)
英文:

so my friend tasked me with changing a string by reversing it, obviously reversing a string gives you just the object id, i managed to find a way to do it but i dont understand what happens under the code. The part i dont get is how join() works with a reversed value, does a value when reversed get converted into a list or tuple before using the join? i didnt clarify to change the string into a list, so what part of the code carries over that change?

a = 'apple'
b = '1'.join(reversed(a))
print(b)

答案1

得分: 1

你误解了调用 reversed 函数时发生的情况:

>>> a = 'apple'
>>> reversed(a)
<reversed object at 0x000002119BDDA3E0>

reversed() 并没有给你一个 "对象标识"。对象标识是你在该对象上调用 id() 时得到的:

>>> id(reversed(a))
2274652699040

reversed() 给你一个特殊的迭代器对象(既不是列表也不是元组),该对象会颠倒你传递给它的内容。这个对象没有实现一个漂亮的 __repr__ 方法,这就是为什么如果你尝试将它原样打印到控制台,你会得到默认的 <CLASS object at ADDRESS> 字符串表示。但是你可以像对待其他迭代器一样对待它。

例如,你可以遍历它:

>>> for i in reversed(a):
...     print(i)
...
e
l
p
p
a

你可以将它转换为一个 list

>>> list(reversed(a))
['e', 'l', 'p', 'p', 'a']

你可以将它作为参数传递给 str.join

>>> ''.join(reversed(a))
'elppa'
英文:

You're misunderstanding what's going on when you call the reversed function:

&gt;&gt;&gt; a = &#39;apple&#39;
&gt;&gt;&gt; reversed(a)
&lt;reversed object at 0x000002119BDDA3E0&gt;

reversed() isn't giving you an "object id". The object id is what you'd get if you called id() on that object:

&gt;&gt;&gt; id(reversed(a))
2274652699040

reversed() is giving you a special iterator object (which is neither a list nor a tuple) that reverses whatever you passed into it. This object doesn't implement a nice __repr__ method, which is why you get the default &lt;CLASS object at ADDRESS&gt; string representation if you just try to print it to the console as-is, but you can do anything with it that you can do with any other iterator.

For example, you can loop over it:

&gt;&gt;&gt; for i in reversed(a):
...     print(i)
...
e
l
p
p
a

you can turn it into a list:

&gt;&gt;&gt; list(reversed(a))
[&#39;e&#39;, &#39;l&#39;, &#39;p&#39;, &#39;p&#39;, &#39;a&#39;]

and you can pass it as an argument to str.join:

&gt;&gt;&gt; &#39;&#39;.join(reversed(a))
&#39;elppa&#39;

huangapple
  • 本文由 发表于 2023年6月16日 10:39:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定