Why wasn't iter.remove implemented in python dicts?

Is there a good reason that iter.remove () is not currently implemented in python dicts?

Let's say I need to remove about half the elements in a set / dictionary. Then I have to either:

  • Copy the whole set / dictionary (n space, n time)
  • Sort through a copy to find the items to be deleted, delete them from the source dictionary (n / 2 plus n / 2 different searches)

Or:

  • Dictionary iterations, adding items to delete in a new set (n space, n time)
  • Iterate over a new set, delete each item from the source dictionary (n / 2 plus n / 2 searches)

Although asymptotically all the time "O (n)", it is terribly inefficient and about 3 times slower compared to a reasonable way:

  • Follow the dictation, removing what you do not want when you go. It really is n time and O (1) space.

At least with the general implementation of hash sets in the form of codes of linked lists, the iterator should be able to delete the element that he just visited without the need for a new search, simply by deleting the node in the linked list.

More importantly, a bad solution also requires O (n) space, which is really bad even for those who tend to shy away from such optimization problems in python.

+4
source share
2 answers

. -, " , ". -, , - 2/3 - 1/3.

, ( 2/3, n/2 ). , :

  • 2.0n, 1.0n, 1.5n: ,
  • 2.0n, 1.0n, 1.5n: ,
  • 1.5n, 1.0n, 1.5n: ,
  • 1.0n, 1.0n, 0.5n:
  • 1.5n, 0.5n, 1.0n: , compact
  • 1.5n, 0.5n, 0.5n:

, , . () , , .


, , , :

  • ( /, ..).
  • , "" , .
  • .
  • , dict ( CPython, 40% , ).

, CPython, , , " C".

, , , , - , , Python , , malloc , , , ?

PyPy, Python .


, , StackOverflow , Python. , - , python-, python-dev / . : 2.x; 3.x, - , , , . , ; Python dicts, , , , , . :


, , " " 1.0n 1.0n .

, , . "" . - . 1.0n . , , 0.5n .

, ,

" ", " ", " ". : ; ; Python; TOOWTDI ; .. , ; , - Python, . , . , , () , () , , , .

, , , , , , - , , , , Python "". , . , Python , Pythonic, , Python, .

, , , ... 'for (a, b) mydict.iteritems() iter', (...) filehandle.

"" -? , , it = iter(mydict.items()), for (a, b) in it:. , , , ? , , . . , StopIteration. list/set/dict, , . - , ?

" () , , ". , , , .

, 1.0 double 0.5. , -, n 1/3 , , -, n/2 2/3 . ?

O (1)

, , , , 0.0n , -0.5n. .

1.0n

, , , , , , . , . , , 0.5n dict, , 0.5n , , . 0.5n, 1.0n, .

, , , , , .

, . , , " /". 99% d = {k: v for k, v in d.items() if pred(k)} - . , ( " , " ) - . , , , , , , .

1,5n, .5n

, . - - , , - - . ( , - dict , , .)

: ", , " - , 1.5n 1.0n, , - .

+3

:

for key in list(mydict.keys()):
    val = mydict[key]
    if <decide drop>(val):
        mydict.pop(key)

:

, invidual lookups , . , ( ).

0

All Articles