可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a list of lists of strings like so:
List1 = [ ['John', 'Doe'], ['1','2','3'], ['Henry', 'Doe'], ['4','5','6'] ]
That I would like to turn into something like this:
List1 = [ [ ['John', 'Doe'], ['1','2','3'] ], [ ['Henry', 'Doe'], ['4','5','6'] ] ]
But I seem to be having trouble doing so.
回答1:
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']]
Edit: Defining a generator function isn't required, you can do the pairing of a list on the fly:
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]
回答2:
This should do what you want assuming you always want to take pairs of the inner lists together.
list1 = [['John', 'Doe'], ['1','2','3'], ['Henry', 'Doe'], ['4','5','6']] output = [list(pair) for pair in zip(list1[::2], list1[1::2])]
It uses zip, which gives you tuples, but if you need it exactly as you've shown, in lists, the outer list comprehension does that.
回答3:
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