在Python 3中对列表中的列表进行分组

时间:2011-09-25 00:16:57

标签: python list python-3.x

我有一个像这样的字符串列表列表:

List1 = [
          ['John', 'Doe'], 
          ['1','2','3'], 
          ['Henry', 'Doe'], 
          ['4','5','6']
        ]

我想变成这样的东西:

List1 = [
          [ ['John', 'Doe'], ['1','2','3'] ],
          [ ['Henry', 'Doe'], ['4','5','6'] ]
        ]

但我似乎遇到了麻烦。

3 个答案:

答案 0 :(得分:4)

List1 = [['John', 'Doe'], ['1','2','3'],
         ['Henry', 'Doe'], ['4','5','6'],
         ['Bob', 'Opoto'], ['10','11','12']]

def pairing(iterable):
    it = iter(iterable)
    itn = it.next
    for x in it :
        yield (x,itn())     

# The generator pairing(iterable) yields tuples:  

for tu in pairing(List1):
    print tu  

# produces:  

(['John', 'Doe'], ['1', '2', '3'])
(['Henry', 'Doe'], ['4', '5', '6'])
(['Bob', 'Opoto'], ['8', '9', '10'])    

# If you really want a yielding of lists:

from itertools import imap
# In Python 2. In Python 3, map is a generator
for li in imap(list,pairing(List1)):
    print li

# or defining pairing() precisely so:

def pairing(iterable):
    it = iter(iterable)
    itn = it.next
    for x in it :
        yield [x,itn()]

# produce   

[['John', 'Doe'], ['1', '2', '3']]
[['Henry', 'Doe'], ['4', '5', '6']]
[['Bob', 'Opoto'], ['8', '9', '10']]

编辑:不需要定义生成器功能,您可以动态配对列表:

List1 = [['John', 'Doe'], ['1','2','3'],
         ['Henry', 'Doe'], ['4','5','6'],
         ['Bob', 'Opoto'], ['8','9','10']]

it = iter(List1)
itn = it.next
List1 = [ [x,itn()] for x in it]

答案 1 :(得分:1)

这应该可以做你想要的,假设你总是想要一起使用内部列表。

list1 = [['John', 'Doe'], ['1','2','3'], ['Henry', 'Doe'], ['4','5','6']] 
output = [list(pair) for pair in zip(list1[::2], list1[1::2])]

它使用zip,它会为你提供元组,但是如果你需要它,就像你在列表中所显示的那样,外部列表理解就是这样。

答案 2 :(得分:0)

这里有8行。我使用元组而不是列表,因为这是“正确”的事情:

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)

演示:

>>> 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

简明方法:

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