python中的自引用列表? [英] Self referential list in python?

查看:43
本文介绍了python中的自引用列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在分析python列表时,当我看到其他编程语言无法做到的事情时,我感到很惊讶.可以说我有一个名为 my_list

While analyzing python list I got surprised when I saw something which is not possible in other programming language. Lets say I have a list called my_list

my_list = [1,2,3,4,5,6,7,8,9,10] 

接下来,当我喜欢的时候

Next when I'm doing like

my_list[9] = my_list  #I didn't seen such things possible in C/C++

当我打印 my_list my_list [9] my_list [9] [9] 时,所有这些都给出相同的结果结果.

And when I'm printing my_list, my_list[9] and my_list[9][9], all these gives the same results.

my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, [...]]
my_list[9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, [...]]
my_list[9][9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, [...]]

我了解到 my_list [9] 指的是相同的列表,分别称为 my_list [...] 表示自我参考列表,即列表指向与您执行 type(my_list [9])时相同的列表,它为我提供 type 作为列表.

What I understood is that my_list[9] is referring to same list called my_list and [...] means self referential list i.e list pointing to same list as when you do type(my_list[9]) it gives me type as list.

[1, 2, 3, 4, 5, 6, 7, 8, 9, [...]]
                              |
             Does it like self referential struct pointer concept of C ?

在我刚才添加的 my_list 示例中,它用于简单的测试运行.我想知道 my_list [9] = my_list 之类的东西如何使python代码性能更好. my_list [9] = my_list 在python中成为可能的背后的实际意图是什么?

Above my_list example I just added for simple test run. I want to know how things like my_list[9] = my_list makes python code performance better. what is the actual intention behind this my_list[9] = my_list making possible in python ?

任何帮助将不胜感激.

推荐答案

这可能是因为列表(与其他容器一样)存储了引用,为什么不引用自身呢?

It's possible because a list (like other containers) store references, and why not a reference of itself?

__ str __ / __ repr __ 函数已受到保护,以避免无限递归,并显示省略号( ... ).

The __str__ / __repr__ functions have been protected against this to avoid infinite recursion, and show an ellipsis instead (...).

为什么有可能?因为这不是不可能的.如果Python要防止这种情况发生,则意味着每次在列表中添加对象时都要检查自引用.这可能是用于维护参考高速缓存的额外O(n)存储开销,也可能是用于执行参考搜索的O(n)时间开销.

Why is it possible? Because it's not impossible. If Python were to prevent that, it would mean checking for self-referencing every time an object is added in the list. This would either be an additional O(n) storage overhead for maintaining a reference cache, or an O(n) time overhead for performing a reference search.

这篇关于python中的自引用列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆