gpt4 book ai didi

python - 列表列表 : Changing all references with one assignment?

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:45 24 4
gpt4 key购买 nike

基本原理:我使用包含多个堆的列表启动脚本。在每一步,我都想“加入”堆,但让两个加入的索引都指向同一个元素。

简而言之,给定一个可变元素列表,例如 list[a] is list[b] 返回 True,我如何分配 (list [a] = [new]) 同时保持 list[a]list[b] 对同一个可变容器的引用?

例如,如果每个堆都由一个字母表示,我们将有

t is ['a', 'b', 'c', 'd']
t is ['ac', 'b', 'ac', 'd'] (0 and 2 merge)
t is ['abc', 'abc', 'abc', 'd'] (0 and 1 merge, but since 0 also refers to 2, it is as if 0/2 and 1 merged... into 0/1/2)

在这个阶段,如果我做了一个 set(map(id, t)),我希望它只有两个元素。

我的问题是我似乎无法影响直接指向的对象,所以我必须遍历整个列表,挑选出与任一合并索引匹配的任何 ID,然后直接分配。

有没有办法改变底层对象而不是所有指向它的指针?

所需行为的完整示例:

>>> my_list = [['a'], ['b'], ['c']]
>>> merge(my_list, 0, 2) # mutates, returns None
>>> my_list
[['a', 'c'], ['b'], ['a', 'c']]
>>> my_list[0] is my_list[2]
True
>>> merge(my_list, 0, 1)
>>> my_list
[['a', 'c', 'b'], ['a', 'c', 'b'], ['a', 'c', 'b']]
>>> my_list[0] is my_list[1]
True
>>> my_list[1] is my_list[2]
True

问题是,如果在 merge 中,我只需调用

my_list[arg1] = my_list[arg2] = my_list[arg1]+my_list[arg2]

它只影响 arg1arg2 的条目。我希望它影响可能指向 my_list[arg1]my_list[arg2] 中的元素的任何其他条目,以便最终 my_list 只是指向同一个大堆的指针的集合,它吸收了所有的小堆。

最佳答案

这与您将要得到的一样接近:

def merge(primary, first, second):
primary[first] += primary[second]
primary[second] = primary[first]

first = ['a']
second = ['b']
third = ['c']

main = [first, second, third]
print(main)
merge(main, 0, 2)
print(main)
assert main[0] is main[2]
merge(main, 0, 1)
print(main)
assert main[1] is main[2]
print(first, second, third)

和打印输出:

[['a'], ['b'], ['c']]
[['a', 'c'], ['b'], ['a', 'c']]
[['a', 'c', 'b'], ['a', 'c', 'b'], ['a', 'c', 'b']]
(['a', 'c', 'b'], ['b'], ['c'])

如您所见,列表元素最终都是同一个对象,但进入主列表的列表却不是。

编辑

不幸的是,如果您没有在每次合并中包含第一个列表元素,这也会失败。

所以这里没有捷径。如果您希望每个元素都是相同的元素,或者只是相等,则必须遍历列表才能完成:

def merge(primary, first, second):
targets = primary[first], primary[second]
result = primary[first] + primary[second]
for index, item in enumerate(primary):
if item in targets:
primary[index] = result

关于python - 列表列表 : Changing all references with one assignment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31197085/

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