在Python3中对列表中的列表进行分组

2024-04-19 14:56:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串列表,如下所示:

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

我想变成这样:

^{pr2}$

但我似乎做不到。在


Tags: 字符串列表johndoelist1henrypr2
3条回答

这里有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)

演示:

^{pr2}$

简明方法:

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

假设您总是希望将成对的内部列表放在一起,这应该可以实现您想要的效果。在

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

它使用zip,这给了你元组,但是如果你需要它就像你所展示的那样,在列表中,外部列表理解就可以做到这一点。在

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

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

^{pr2}$

相关问题 更多 >