Python : Get many list from a list [duplicate]

萝らか妹 提交于 2019-12-01 11:32:10

The itertools module documentation. Read it, learn it, love it.

Specifically, from the recipes section:

import itertools

def grouper(n, iterable, fillvalue=None):
  "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  args = [iter(iterable)] * n
  return itertools.izip_longest(fillvalue=fillvalue, *args)

Which gives:

>>> tuple(grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5, None))

which isn't quite what you want...you don't want the None in there...so. a quick fix:

>>> tuple(tuple(n for n in t if n) for t in grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5))

If you don't like typing the list comprehension every time, we can move its logic into the function:

def my_grouper(n, iterable):
  "my_grouper(3, 'ABCDEFG') --> ABC DEF G"
  args = [iter(iterable)] * n
  return tuple(tuple(n for n in t if n)
       for t in itertools.izip_longest(*args))

Which gives:

>>> tuple(my_grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5))

Done.

Here's how I'd do it. Iteration, but in a list comprehension. Note the type gets mixed; this may or may not be desired.

def sublist(seq, length):
    return [seq[i:i + length] for i in xrange(0, len(seq), length)]

Usage:

>>> sublist((1, 2, 3, 4, 5), 1)
[(1,), (2,), (3,), (4,), (5,)]

>>> sublist([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]

>>> sublist('12345', 3)
['123', '45']

>>> sublist([1, 2, 3, 4, 5], 73)
[[1, 2, 3, 4, 5]]

>>> sublist((1, 2, 3, 4, 5), 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in sublist
ValueError: xrange() arg 3 must not be zero

Of course, you can easily make it produce a tuple too if you want - replace the list comprehension [...] with tuple(...). You could also replace seq[i:i + length] with tuple(seq[i:i + length]) or list(seq[i:i + length]) to make it return a fixed type.

From the python docs on the itertools module:

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Example:

>>> tuple(grouper(3, (1, 2, 3, 4, 5, 6, 7)))
((1, 2, 3), (4, 5, 6), (7, None, None))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!