按列表分组python

时间:2017-09-19 19:53:40

标签: python list

tests= ['test-2017-09-19-12-06',
        'test-2017-09-19-12-05',
        'test-2017-09-12-12-06',
        'test-2017-09-12-12-05',
        'test-2017-09-07-12-05',
        'test-2017-09-06-12-07']

所以我有上面的列表,我怎么能按列表分组,这样我就可以得到一个如下所示的列表:

[['test-2017-09-19-12-06','test-2017-09-19-12-05'],
 ['test-2017-09-12-12-06','test-2017-09-12-12-05'],
 ['test-2017-09-07-12-05'],
 ['test-2017-09-06-12-07']]

我确实尝试了以下代码,但我得到了不同的结果,其中每个字符串值都成为自己的列表而不是分组依据。

from itertools import groupby

print([list(j) for i, j in groupby(tests)])

2 个答案:

答案 0 :(得分:0)

您可以按尺寸拆分

tests = ['test-2017-09-19-12-06',
        'test-2017-09-19-12-05',
        'test-2017-09-12-12-05',
        'test-2017-09-12-12-05',
        'test-2017-09-07-12-05',
        'test-2017-09-06-12-07']
size = 2
[tests[i:i+size] for i  in range(0, len(tests), size)]

答案 1 :(得分:0)

请参阅范围0:15,您可以使用它来确定哪个分段用于分组。

tests= ['test-2017-09-19-12-06',
        'test-2017-09-19-12-05',
        'test-2017-09-12-12-06',
        'test-2017-09-12-12-05',
        'test-2017-09-07-12-05',
        'test-2017-09-06-12-07']

pprint.pprint([list(j[1]) for j in groupby(tests,lambda i:i[0:15])])
[['test-2017-09-19-12-06', 'test-2017-09-19-12-05'],
 ['test-2017-09-12-12-05', 'test-2017-09-12-12-05'],
 ['test-2017-09-07-12-05'],
 ['test-2017-09-06-12-07']]