我有以下列表:
a = [['A','R.1',1],['B','R.2',1],['B','R.2',2],['C','R.2',3],
['C','C.1',4],['C','C.1',5],['A','C.1',8],['B','C.1',9],
['B','C.1',1],['A','R.3',2],['C','R.1',3],['A','R.2',4],
['C','R.1',5],['A','R.1',1],['C','R.2',5],['A','R.1',8]]
我需要以某种方式对其进行分组以生成以下结果:
[['A', 'C.1', 1],
['A', 'R.1', 3],
['A', 'R.2', 1],
['A', 'R.3', 1],
['B', 'C.1', 2],
['B', 'R.2', 2],
['C', 'C.1', 2],
['C', 'R.1', 2],
['C', 'R.2', 2]]
第三列是第一列和第二列匹配的行数。 从原始列表中,第三列的值可以忽略不计。
我已经尝试通过“for”嵌套和“列表理解”,但我无法得出任何结果。
有没有人知道如何解决这个问题?
答案 0 :(得分:1)
使用collections.defaultdict
对象:
import collections
a = [['A','R.1',1],['B','R.2',1],['B','R.2',2],['C','R.2',3],
['C','C.1',4],['C','C.1',5],['A','C.1',8],['B','C.1',9],
['B','C.1',1],['A','R.3',2],['C','R.1',3],['A','R.2',4],
['C','R.1',5],['A','R.1',1],['C','R.2',5],['A','R.1',8]]
d = collections.defaultdict(int)
for l in a:
d[(l[0],l[1])] += 1
result = [list(k)+[v] for k,v in sorted(d.items())]
print(result)
输出:
[['A', 'C.1', 1], ['A', 'R.1', 3], ['A', 'R.2', 1], ['A', 'R.3', 1], ['B', 'C.1', 2], ['B', 'R.2', 2], ['C', 'C.1', 2], ['C', 'R.1', 2], ['C', 'R.2', 2]]
只是为了“漂亮”的印刷品:
import pprint
...
pprint.pprint(result)
输出:
[['A', 'C.1', 1],
['A', 'R.1', 3],
['A', 'R.2', 1],
['A', 'R.3', 1],
['B', 'C.1', 2],
['B', 'R.2', 2],
['C', 'C.1', 2],
['C', 'R.1', 2],
['C', 'R.2', 2]]
答案 1 :(得分:0)
与@RomanPerekhrest类似,我使用了Counter
:
from collections import Counter
a = [['A','R.1',1],['B','R.2',1],['B','R.2',2],['C','R.2',3],
['C','C.1',4],['C','C.1',5],['A','C.1',8],['B','C.1',9],
['B','C.1',1],['A','R.3',2],['C','R.1',3],['A','R.2',4],
['C','R.1',5],['A','R.1',1],['C','R.2',5],['A','R.1',8]]
def transform(table):
c = Counter(map(lambda c: tuple(c[:-1]), table))
return sorted(map(lambda p: list(p[0]) + [p[1]], c.items()))
print(transform(a))