thể trùng lặp:
Python: Retrieve items from a setCó cách nào để lấy một vật phẩm từ một bộ trong thời gian O (1) không?
Xét đoạn mã sau:
>>> item1 = (1,)
>>> item2 = (2,)
>>> s = set([item1, item2])
>>> s
set([(2,), (1,)])
>>> new_item = (1,)
>>> new_item in s
True
>>> new_item == item1
True
>>> new_item is item1
False
Vì vậy new_item
là trong s
vì nó tương đương với một trong các mục của nó, nhưng nó là một đối tượng khác.
Điều tôi muốn là nhận item1
từ s
được cung cấp new_item
nằm trong s
.
Một giải pháp tôi đã đưa ra rất đơn giản nhưng không phải là rất hiệu quả:
def get_item(s, new_item):
for item in s:
if item == new_item:
return item
>>> get_item(s, new_item) is new_item
False
>>> get_item(s, new_item) is item1
True
Một giải pháp khác có vẻ hiệu quả hơn nhưng thực tế không làm việc:
def get_item_using_intersection1(s, new_item):
return set([new_item]).intersection(s).pop()
Cũng không phải cái này:
def get_item_using_intersection2(s, new_item):
return s.intersection(set([new_item])).pop()
Do giao lộ hoạt động theo cách không xác định:
>>> get_item_using_intersection1(s, new_item) is new_item
True
>>> get_item_using_intersection1(s, new_item) is item1
False
>>> get_item_using_intersection2(s, new_item) is new_item
True
>>> get_item_using_intersection2(s, new_item) is item1
False
Nếu vấn đề này, tôi đang sử dụng Python 2.7 x64 trên Windows 7, nhưng tôi cần một giải pháp đa nền tảng.
Xin cảm ơn tất cả mọi người. Tôi đã đưa ra giải pháp tạm thời sau:
class SearchableSet(set):
def find(self, item):
for e in self:
if e == item:
return e
sẽ được thay thế trong tương lai với các giải pháp sau đây (mà là rất không đầy đủ ngay bây giờ):
class SearchableSet(object):
def __init__(self, iterable=None):
self.__data = {}
if iterable is not None:
for e in iterable:
self.__data[e] = e
def __iter__(self):
return iter(self.__data)
def __len__(self):
return len(self.__data)
def __sub__(self, other):
return SearchableSet(set(self).__sub__(set(other)))
def add(self, item):
if not item in self:
self.__data[item] = item
def find(self, item):
return self.__data.get(item)
Nhưng ... "Giải pháp không hiệu quả" mà bạn đưa ra đã là tuyến tính. – kennytm
Tôi nghĩ rằng anh ấy có nghĩa là * liên tục * thời gian –
@KennyTM, cảm ơn bạn, tôi đã chỉnh sửa tiêu đề câu hỏi của mình. – utapyngo