使用递归枚举列表,python
我正在尝试使用递归枚举列表,但很难做到这一点。 如果有人能指出我正确的方向,我将不胜感激! :)
def my_enumerate(items, start_index=0):
"""my enumerate"""
result = []
if not items:
return []
else:
a = (start_index, items[0])
result.append(a)
my_enumerate(items[1:], start_index + 1)
return result
ans = my_enumerate([10, 20, 30])
print(ans)**strong text**
I'm trying to enumerate the list using recursion and am having a hard time doing so.
If anyone can point me in the right direction that would be greatly appreciated! :)
def my_enumerate(items, start_index=0):
"""my enumerate"""
result = []
if not items:
return []
else:
a = (start_index, items[0])
result.append(a)
my_enumerate(items[1:], start_index + 1)
return result
ans = my_enumerate([10, 20, 30])
print(ans)**strong text**
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
以下更简洁:
Try:
The following is more concise:
当您使用递归并在函数内声明
result = []
时,每次它都会变空,因此您会丢失所有先前的结果。如果您确实希望这个工作正常,那么还有另一种方法,如果您想全局使用该列表,则可以将结果设置为 global ,如下所示:
但是当您不想这样做时, @CocompleteHippopotamus 答案将起作用使用全局关键字。
As you are using recursion and you are declaring
result = []
within a function so everytime it simply gets empty so you lose all previous results.If you want exactly this to work there is also another way that by making the result as global if you wanted to use that list globally like below:
But @CocompleteHippopotamus answer will work when you don't want to use a global keyword.