通过引用传递时验证 python 列表中完全相同的变量

Verifying exactly the same variable in python list when passing by reference

获取嵌套列表: list = [[foo, foo], [foo, foo]], [foo, foo]].

我将 list 传递给一个函数,但我也分别通过引用将第二个嵌套列表作为 list[1].

传递给同一函数

然后,在随机索引函数中,我向 list 添加了 3 个 [foo, foo]

是否可以识别 list 中的哪个 [foo, foo] 是我传递给函数的那个​​?

换句话说,我想得到原来[foo, foo]的新索引我在现在修改的list.

中单独传递了

您要查找的是 is,它测试两个变量是否引用同一对象。

在 iPython shell 中展示:

In [1]: list = [['foo', 'foo'], ['foo', 'foo'], ['foo', 'foo']]

In [2]: sublist = list[1]

In [3]: sublist is list[1]
Out[3]: True

In [5]: list.insert(1, ['foo', 'foo'])

In [6]: list
Out[6]: [['foo', 'foo'], ['foo', 'foo'], ['foo', 'foo'], ['foo', 'foo']]

In [7]: list.insert(1, ['foo', 'foo'])

In [8]: list
Out[8]: 
[['foo', 'foo'],
 ['foo', 'foo'],
 ['foo', 'foo'],
 ['foo', 'foo'],
 ['foo', 'foo']]

In [9]: sublist is list [1]
Out[9]: False

In [10]: for count, l in enumerate(list):
   ...:     if l is sublist:
   ...:         print(count)
   ...: 
3

In [11]: sublist is list[3]
Out[11]: True

Forensic 有一个很好的答案。您还可以尝试修改函数以包含有关哪个索引具有原始元素的信息的方法。如果您能够修改此功能,这可能比测试长列表中的项目更有效。

import random
foo = 4
items = [[foo, foo], [foo, foo, foo], [foo, foo]]

# parameter "index" is index of the item to keep track of
def add_items(items, index):
    new_index = -1

    for _ in range(2):
        insert_at = random.choice(range(len(items)))
        # shift to the right if inserting before
        new_index = index if insert_at > index else index + 1
        # modify items; insert a new item foo at index insert_at
        items.insert(insert_at, foo)
        
    return items, new_index

print(add_items(items, 1))

输出:

([4, [4, 4], 4, [4, 4, 4], [4, 4]], 1)