获取在python中操作原始列表的多维列表

时间:2013-11-30 06:21:11

标签: python numpy

我想基于图块对文件列表进行分组。

files = ['tile1_band1','tile1_band2','tile2_band1','tile2_band2']
tiles = [file[0:5] for file in files]
for tile in tiles:
    new_files = [file for file in files if tile in file]
    print (new_files)

结果应完全如下(二维列表):

[['tile1_band1', 'tile1_band2'], ['tile2_band1', 'tile2_band2']]

3 个答案:

答案 0 :(得分:3)

使用zip builtin并在切片中添加一个步骤:

In [26]: a = range(10)

In [27]: zip(a[::2], a[1::2])
Out[27]: [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

答案 1 :(得分:2)

使用itertools.groupby

>>> import itertools
>>> files = ['tile1_band1','tile1_band2','tile2_band1','tile2_band2']
>>> [list(grp) for key, grp in itertools.groupby(files, key=lambda f: f[:5])]
[['tile1_band1', 'tile1_band2'], ['tile2_band1', 'tile2_band2']]

如果tile1部分的长度可变,请使用str.split('_', 1)[0]作为密钥。

>>> [list(grp) for key, grp in itertools.groupby(files, key=lambda f: f.split('_', 1)[0])]
[['tile1_band1', 'tile1_band2'], ['tile2_band1', 'tile2_band2']]

答案 2 :(得分:2)

>>> import itertools
>>> files = ['tile1_band1','tile1_band2','tile2_band1','tile2_band2']
>>> [list(grp) for key, grp in itertools.groupby(files, key=lambda f: f.split('_')[0])]
[['tile1_band1', 'tile1_band2'], ['tile2_band1', 'tile2_band2']]

上述代码比falsetru更灵活,但这是对原始答案的改进。