Python: access to collection items

Let's say I have a set of myset user objects that can be equal, although their references are different ( a == b and a is not b ). Now, if I add(a) to a set, Python correctly assumes that a in myset and b in myset , although there is only a len(myset) == 1 object in the set.

It is clear. But is it now possible to extract the value of a from the set using only b ? Suppose the objects are mutable, and I want to change them, forgetting about the direct link to a . In other words, I am looking for the operation myset[b] , which will definitely return the member a for the set.

It seems to me that the set type cannot do this (faster than repeating through all its members). If so, is there at least effective work?

+6
source share
3 answers

I don't think that set supports getting an element O (1) times, but you can use a dict instead.

 d = {} d[a] = a retrieved_a = d[b] 
+5
source

If you have only myset and b , then from this point of view you will not have access to a , because it does not exist. If you create several mutable objects and add one of them to myset , then the others are not "known" when you are dealing with just myset or the object you added.

If you want to change a and b , then you need to track both objects somewhere.

0
source

Perhaps it:

 (myset - (myset - set([b]))).pop() is a 
0
source

Source: https://habr.com/ru/post/918286/


All Articles