Python 使用列表列表中某列的公共值分组到子列表中
列表元素格式:(x0,y0,x1,y1,“字”,块号,行号,字号) 我需要按“y1”分组,其值和形式如下所示:Python 使用列表列表中某列的公共值分组到子列表中,python,python-3.x,Python,Python 3.x,列表元素格式:(x0,y0,x1,y1,“字”,块号,行号,字号) 我需要按“y1”分组,其值和形式如下所示: required = [ [ (518.1566162109375, 381.6667175292969, 537.3801879882812, 391.70867919921875, 'cost', 19, 0, 11), (542.1559448242188, 381.6667175292969, 556.5796508789062, 391.70867919921875, 'a
required = [
[
(518.1566162109375, 381.6667175292969, 537.3801879882812, 391.70867919921875, 'cost', 19, 0, 11),
(542.1559448242188, 381.6667175292969, 556.5796508789062, 391.70867919921875, 'and', 19, 0, 12)
],
[
(81.36001586914062, 390.6634826660156, 124.58306121826172, 400.7054443359375, 'inventory', 19, 1, 0),
(129.35882568359375, 390.6634826660156, 167.78199768066406, 400.7054443359375, 'control,', 19, 1, 1)
]
]
请给我建议一些实现它的最佳方法。使用&:
输出:
[
[(518.1566162109375, 381.6667175292969, 537.3801879882812, 391.70867919921875, 'cost', 19, 0, 11), (542.1559448242188, 381.6667175292969, 556.5796508789062, 391.70867919921875, 'and', 19, 0, 12)],
[(81.36001586914062, 390.6634826660156, 124.58306121826172, 400.7054443359375, 'inventory', 19, 1, 0), (129.35882568359375, 390.6634826660156, 167.78199768066406, 400.7054443359375, 'control,', 19, 1, 1)]
]
使用
itertools
:
import itertools
byloc = lambda x: x[3]
new_list = [list(v) for k,v in itertools.groupby(given, key=byloc)]
new_list
[
[(518.1566162109375, 381.6667175292969, 537.3801879882812, 391.70867919921875, 'cost', 19, 0, 11), (542.1559448242188, 381.6667175292969, 556.5796508789062, 391.70867919921875, 'and', 19, 0, 12)],
[(81.36001586914062, 390.6634826660156, 124.58306121826172, 400.7054443359375, 'inventory', 19, 1, 0), (129.35882568359375, 390.6634826660156, 167.78199768066406, 400.7054443359375, 'control,', 19, 1, 1)]
]
import itertools
byloc = lambda x: x[3]
new_list = [list(v) for k,v in itertools.groupby(given, key=byloc)]
new_list
[[(518.1566162109375,
381.6667175292969,
537.3801879882812,
391.70867919921875,
'cost',
19,
0,
11),
(542.1559448242188,
381.6667175292969,
556.5796508789062,
391.70867919921875,
'and',
19,
0,
12)],
[(81.36001586914062,
390.6634826660156,
124.58306121826172,
400.7054443359375,
'inventory',
19,
1,
0),
(129.35882568359375,
390.6634826660156,
167.78199768066406,
400.7054443359375,
'control,',
19,
1,
1)]]