python将每个第3个值的字符串拆分成一个嵌套格式

时间:2014-04-08 09:11:17

标签: python

我有一个这样的清单:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

我希望它看起来像这样

[['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]

最有效的方法是什么?

编辑: 怎么样呢?

[['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]

- >

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

6 个答案:

答案 0 :(得分:12)

你可以通过简单的列表理解来做你想做的事。

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [a[i:i+3] for i in range(0, len(a), 3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

如果您希望填充最后一个子列表,可以在列表理解之前执行此操作:

>>> padding = 0
>>> a += [padding]*(3-len(a)%3)

将这些组合成一个单一的功能:

def group(sequence, group_length, padding=None):
    if padding is not None:
        sequence += [padding]*(group_length-len(sequence)%group_length)
    return [sequence[i:i+group_length] for i in range(0, len(sequence), group_length)]

走另一条路:

def flatten(sequence):
    return [item for sublist in sequence for item in sublist]

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> flatten(a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

答案 1 :(得分:4)

如果您可以使用numpy,请尝试x.reshape(-1, 3)

In [1]: import numpy as np
In [2]: x = ['a','b','c','d','e','f','g','h','i']
In [3]: x = np.array(x)
In [4]: x.reshape(-1, 3)
Out[4]: 
array([['a', 'b', 'c'],
       ['d', 'e', 'f'],
       ['g', 'h', 'i']], 
      dtype='|S1')

如果数据足够大,则此代码更有效。

<强>更新

附加cProfile结果以解释更高效

import cProfile
import numpy as np

a = range(10000000*3)

def impl_a():
    x = [a[i:i+3] for i in range(0, len(a), 3)]

def impl_b():
    x = np.array(a)
    x = x.reshape(-1, 3)

print("cProfile reuslt of impl_a()")
cProfile.run("impl_a()")
print("cProfile reuslt of impl_b()")
cProfile.run("impl_b()")

输出

cProfile reuslt of impl_a()
      5 function calls in 15.614 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    0.499    0.499   15.614   15.614 <string>:1(<module>)
     1   14.968   14.968   15.114   15.114 impla.py:6(impl_a)
     1    0.000    0.000    0.000    0.000 {len}
     1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
     1    0.146    0.146    0.146    0.146 {range}


cProfile reuslt of impl_b()
     5 function calls in 3.142 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    0.000    0.000    3.142    3.142 <string>:1(<module>)
     1    0.000    0.000    3.142    3.142 impla.py:9(impl_b)
     1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
     1    0.000    0.000    0.000    0.000 {method 'reshape' of 'numpy.ndarray' objects}
     1    3.142    3.142    3.142    3.142 {numpy.core.multiarray.array}

答案 2 :(得分:3)

您可以将grouper recipe from itertoolslist comprehension

一起使用
from itertools import izip_longest # or zip_longest for Python 3.x

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args) # see note above

in_ = [1, 2, 3, 4, 5, 6, 7, 8, 9]

out = [list(t) for t in grouper(in_, 3)]

答案 3 :(得分:2)

我的解决方案:

>>> list=[1,2,3,4,5,6,7,8,9,10]
>>> map(lambda i: list[i:i+3], range(0,len(list),3))
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

答案 4 :(得分:1)

使用itertools,更具体地说,使用Recipes提到的函数grouper

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print [list(x) for x in grouper(a, 3)]

打印

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

答案 5 :(得分:1)

我已将所有已回答的方法运行到基准测试并找到最快的方法。

样本量 999999(1&lt; = x&lt; = 258962)

Python: Python 2.7.5 | Anaconda 1.8.0(32位)(IPython)

操作系统:Windows 7 32位 @ Core i5 / 4GB RAM

样本生成代码

import random as rd
lst = [rd.randrange(1,258963) for n in range(999999)]

来自@Scorpion_God的解决方案:

>>> %timeit x = [lst[i:i+3] for i in range(0, len(lst), 3)]
10 loops, best of 3: 114 ms per loop

来自@mskimm的解决方案:

>>>  %timeit array = np.array(lst)
10 loops, best of 3: 127 ms per loop
>>> %timeit array.reshape(-1,3)
1000000 loops, best of 3: 679 ns per loop

来自@jonrsharpe / @Carsten的解决方案:

>>> %timeit out = [list(t) for t in grouper(lst, 3)]
10 loops, best of 3: 158 ms per loop

所以,似乎在IPython(Anaconda)上, list-comprehension比itertools / izip_longest / grouper方法快快30%

P.S。我想,这个结果在CPython运行时会有所不同,我也希望补充一下。