संभव डुप्लिकेट: क्योंकि यह अपनी वस्तुओं में से एक के बराबर हैक्या ओ (1) समय में किसी सेट से आइटम प्राप्त करने का कोई तरीका है?
>>> 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
तो
new_item
s
में है, लेकिन यह है:
Python: Retrieve items from a set
निम्नलिखित कोड पर विचार करें एक अलग वस्तु।
क्या मैं चाहता हूँ s
से item1
प्राप्त करने के लिए दिए गए new_item
s
में है।
एक समाधान मैं के साथ आए हैं सीधा लेकिन बहुत ही कुशल नहीं है:
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
एक अन्य समाधान अधिक कुशल लगता है, लेकिन वास्तव में काम नहीं करता है:
def get_item_using_intersection1(s, new_item):
return set([new_item]).intersection(s).pop()
न ही यह एक:
def get_item_using_intersection2(s, new_item):
return s.intersection(set([new_item])).pop()
क्योंकि चौराहे एक अपरिभाषित तरीके से काम करता है:
>>> 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
यदि यह मायने रखता है, तो मैं विंडोज 7 पर पायथन 2.7 x64 का उपयोग कर रहा हूं, लेकिन मुझे एक क्रॉस-प्लेटफ़ॉर्म समाधान की आवश्यकता है।
सभी के लिए धन्यवाद।
class SearchableSet(set):
def find(self, item):
for e in self:
if e == item:
return e
जो निम्नलिखित समाधान के साथ भविष्य में बदल दिया जाएगा (जो अभी बहुत अधूरा है): मैं निम्नलिखित अस्थायी समाधान के साथ आया था
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)
लेकिन ... "अपर्याप्त समाधान" आप पहले से ही रैखिक हैं। – kennytm
मुझे लगता है कि उसका मतलब है * स्थिर * समय –
@ केनीटीएम, धन्यवाद, मैंने अपना प्रश्न शीर्षक संपादित किया है। – utapyngo