Python,如何传递对列表列表的引用(而不是值)

Python, how to pass reference to list of list (not value)

提问人:CatalunaLilith 提问时间:1/23/2021 最后编辑:CatalunaLilith 更新时间:1/23/2021 访问量:77

问:

我想传递对 int 列表的引用,而不是 int 值本身。

我有一个 ints 列表,它代表一个根优先的二叉树,我称之为 我正在构建一个列表,当我走下来时,它充满了对格式的引用,问题是当我尝试打印或传递时,它是一个 int 值列表, 不是我放入其中的参考资料列表。aTriangle pathaTriangle pathaTriangleaTriangle[i][j]path

例如

test_triangle = [[1], [2, 3], [4, 5, 6]]
test_list = [test_triangle[0][0], test_triangle[1][0]]
print(test_list)

打印出来(同样,传递test_list传递值)[1, 2]

但我想要[test_triangle[0][0], test_triangle[1][0]]

如何构建 STAY 作为引用的引用列表?或者,如果这是不可行的,如果有另一种方法可以让我保留与该值关联的两个索引的tract,因为这些索引值对后续步骤很重要。

Python 列表 通过引用传递

评论

2赞 1/23/2021
您似乎误解了 python 列表的工作原理,当您索引列表列表时,您得到的实际上是对包含列表的引用。但是当你打印它时,python 足够聪明,可以打印引用列表的 repr,而不是像 c/c++ 中那样打印列表的地址
2赞 Countour-Integral 1/23/2021
我有没有另一种方法可以保留与值 yes 相关的两个索引的 tract 将索引存储在 中。test_list
0赞 1/23/2021
“我有没有另一种方法可以保持与该值相关的两个索引的 tract”..查找 xarray,xarray 中包含的元素存储它们所包含的索引。
0赞 juanpa.arrivillaga 1/23/2021
Python 总是有引用语义(尽管它既不是按值调用也不是按引用调用)
0赞 CatalunaLilith 1/23/2021
@Countout-Integral你知道吗,这是完美的。这是保存索引的简单、直接的方法,当我最终需要该值时,我可以轻松调用它。谢谢!

答:

1赞 gsb22 1/23/2021 #1

你在寻找这样的东西吗?

免责声明 -> 这是纯粹的黑客,我建议寻找更复杂的 python 模块/库。

test_triangle = [[1], [2, 3], [4, 5, 6]]
test_list = (test_triangle[0][0], test_triangle[1][0])

values_and_indexes = {}

for index, value in enumerate(test_triangle):
    for _i, _v in enumerate(value):
        values_and_indexes[f"test_triangle[{index}][{_i}]"] = _v

print(values_and_indexes)

输出

{'test_triangle[0][0]': 1, 'test_triangle[1][0]': 2, 'test_triangle[1][1]': 3, 'test_triangle[2][0]': 4, 'test_triangle[2][1]': 5, 'test_triangle[2][2]': 6}