python list concatenation efficiency

前端 未结 6 1382
陌清茗
陌清茗 2020-12-16 13:07

What is the most efficient way to concatenate two lists list_a and list_b when:

  • list_b items have to be placed before
6条回答
  •  萌比男神i
    2020-12-16 13:31

    Given that

    list_a = list_b + list_a
    

    works for your purposes, it follows that you don't actually need the list_a object itself to store all the data in list_a - you just need it called list_a (ie, you don't have, or don't care about, any other variables you have floating around that might refer to that same list).

    If you also happen not to care about it being exactly a list, but only about it being iterable, then you can use itertools.chain:

    list_a = itertools.chain(list_b, list_a)
    

    If you do care about some list things, you could construct a similar type of thing to chain that behaves like a list - something like:

    class ListChain(list):
        def __init__(self, *lists):
            self._lists = lists
    
        def __iter__(self):
            return itertools.chain.from_iterable(self._lists)
    
        def __len__(self):
            return sum(len(l) for l in self._lists)
    
        def append(self, item):
            self._lists[-1].append(item)
    
        def extend(self, iterable):
            self._lists.append(list(iterable))
    
        def __getitem__(self, item):
           for l in self._lists:
               if item < len(l):
                  return l[item]
               item -= len(l)
           else:
              raise IndexError
    

    etc. This would take a lot of effort (possibly more than its worth) for this to work in all cases - eg, handling slices and negative indexes comes to mind. But for very simple cases, this approach can avoid a lot of copying list contents around.

提交回复
热议问题