Grouping lists within lists in Python 3

前端 未结 3 1256
不知归路
不知归路 2021-01-27 05:32

I have a list of lists of strings like so:

List1 = [
          [\'John\', \'Doe\'], 
          [\'1\',\'2\',\'3\'], 
          [\'Henry\', \'Doe\'], 
          [         


        
3条回答
  •  情深已故
    2021-01-27 05:50

    Here it is in 8 lines. I used tuples rather than lists because it's the "correct" thing to do:

    def pairUp(iterable):
        """
            [1,2,3,4,5,6] -> [(1,2),(3,4),(5,6)]
        """
        sequence = iter(iterable)
        for a in sequence:
            try:
                b = next(sequence)
            except StopIteration:
                raise Exception('tried to pair-up %s, but has odd number of items' % str(iterable))
            yield (a,b)
    

    Demo:

    >>> list(pairUp(range(0)))    
    []
    
    >>> list(pairUp(range(1)))
    Exception: tried to pair-up [0], but has odd number of items
    
    >>> list(pairUp(range(2)))
    [(0, 1)]
    
    >>> list(pairUp(range(3)))
    Exception: tried to pair-up [0, 1, 2], but has odd number of items
    
    >>> list(pairUp(range(4)))
    [(0, 1), (2, 3)]
    
    >>> list(pairUp(range(5)))
    Exception: tried to pair-up [0, 1, 2, 3, 4], but has odd number of items
    

    Concise method:

    zip(sequence[::2], sequence[1::2])
    # does not check for odd number of elements
    

提交回复
热议问题