3 回答
TA贡献1900条经验 获得超5个赞
对于您的 2d 列表结构,您可以使用 zip 和列表理解
lst = [['dragon', 11], ['dragon', 111], ['stage_1', 1], ['stage_1', 2], ['stage_2', 10], ['stage_2', 12]]
k, v = zip(*lst)
result = [[k[i], v[i:i+2]] for i in range(0, len(k), 2)]
print(result)
输出
[['dragon', (11, 111)], ['stage_1', (1, 2)], ['stage_2', (10, 12)]]
性能比较
1.列表理解/压缩
k, v = zip(*lst)
result = [[k[i], v[i:i+2]] for i in range(0, len(k), 2)]
100000 loops, best of 3: 3.72 µs per loop (using timeit)
2.字典
d = defaultdict(list)
for k, v in lst:
d[k].append(v)
groups = list(map(list, d.items()))
100000 loops, best of 3: 5.85 µs per loop (using timeit)
结果:列表理解速度快约 57%
TA贡献1807条经验 获得超9个赞
有collections.defaultdict对象:
from collections import defaultdict
lst = [['dragon', 11], ['dragon', 111], ['stage_1', 1], ['stage_1', 2], ['stage_2', 10], ['stage_2', 12]]
d = defaultdict(list)
for k, v in lst:
d[k].append(v)
groups = list(map(list, d.items()))
print(groups)
输出:
[['dragon', [11, 111]], ['stage_1', [1, 2]], ['stage_2', [10, 12]]]
TA贡献1777条经验 获得超3个赞
我认为最好为您的情况使用字典,如下所示
d = { }
for key,value in ls:
d[key] = d.get(key, []) + [value]
print(d)
d.items()如果需要列表,可以使用获取元组列表
添加回答
举报