gpt4 book ai didi

python - 为什么会出现这个输出?

转载 作者:行者123 更新时间:2023-11-28 19:50:39 26 4
gpt4 key购买 nike

def function(s):
if len(s) == 1:
print s[0],
else:
function(s[1:])
print s[0],

function("1234") 结束打印 4 3 2 1

为什么会这样?在函数中,显然不满足第一个条件。在 else 条件下,s[1:] 被放入 s,但它的长度不是 1。我只是看不到 s[0] 之外的任何东西> 将打印到屏幕上。该函数中没有任何内容看起来像打印 s[1:],更不用说反向打印了。我很困惑。

最佳答案

>>> def function(s):
... print 's is currently %r' % s
... if len(s) == 1:
... print s[0],
... else:
... function(s[1:])
... print s[0],
...
>>> function("1234")
s is currently '1234'
s is currently '234'
s is currently '34'
s is currently '4'
4 3 2 1

这是一个递归函数,它在打印 s[0] 之前再次调用自身,因此它打印出的项目被反转。

这是一个可能更有帮助的示例。

>>> def function(s):
... print 's is currently %r' % s
... if len(s) > 1:
... print 'calling function again with %r as s' % s[1:]
... function(s[1:])
... print s[0],
...
>>> function('1234')
s is currently '1234'
calling function again with '234' as s
s is currently '234'
calling function again with '34' as s
s is currently '34'
calling function again with '4' as s
s is currently '4'
4 3 2 1

关于python - 为什么会出现这个输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10239716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com