检查项目是否已经在具有参照相等性的列表中

问题描述 投票:0回答:1

我想检查一个项目是否已经在具有引用相等而不是结构相等的列表中。

为清楚起见:

2个项目之间的参照相等性用item1 is item2

item1 == item2检查结构相等性

检查项目是否已在列表中的结构相等性很容易地像这样:

item in list

因此,我正在寻找具有参照相等性的等效行。是否可以不遍历列表中的每个项目?

如何执行此操作的示例(仅作澄清):

def get_all_items_in_list(items):
   all_items = []
   for item in items:
       if not item in all_items:
           all_items.append(item)
   return all_items

# setup
a = (1, [])
b = (1, [])
print(a is b)    # prints False
items = [a, a, b]
print(get_all_items_in_list(items))  # should print [(1, []), (1, [])] but prints [(1, [])]
python arrays equality
1个回答
0
投票

尝试一下,

a=10
b=20
c=30
l=[id(a),id(b),id(c)]
id(a) in l
© www.soinside.com 2019 - 2024. All rights reserved.