【发布时间】:2026-01-21 13:15:01
【问题描述】:
问题
我有兴趣找到一种更有效(代码复杂性、速度、内存使用、理解、生成器)的方法来减少两个元素元组的列表,其中第一个元素可能在元素,到列表字典。
from copy import deepcopy
a = [('a', 'cat'), ('a', 'dog'), ('b', 'pony'), ('c', 'hippo'), ('c','horse'), ('d', 'cow')]
b = {x[0]: list() for x in a}
c = deepcopy(b)
for key, value in b.items():
for item in a:
if key == item[0]:
c[key].append(item[1])
print(a)
print(c)
[('a', 'cat'), ('a', 'dog'), ('b', 'pony'), ('c', 'hippo'), ('c', '马'), ('d', '牛')]
{'a': ['cat', 'dog'], 'b': ['pony'], 'c': ['hippo', 'horse'], 'd': ['cow' ]}
答案测试
from collections import defaultdict
from itertools import groupby
from operator import itemgetter
import timeit
timings = dict()
def wrap(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
a = [('a', 'cat'), ('a', 'dog'), ('b', 'pony'), ('c', 'hippo'), ('c','horse'), ('d', 'cow')]
# yatu's solution
def yatu(x):
output = defaultdict(list)
for item in x:
output[item[0]].append(item[1])
return output
# roseman's solution
def roseman(x):
d = defaultdict(list)
for key, value in a:
d[key].append(value)
return d
# prem's solution
def prem(a):
result = {k: [v for _,v in grp] for k,grp in groupby(a, itemgetter(0))}
return result
# timings
yatus_wrapped = wrap(yatu, a)
rosemans_wrapped = wrap(roseman, a)
prems_wrapped = wrap(prem, a)
timings['yatus'] = timeit.timeit(yatus_wrapped, number=100000)
timings['rosemans'] = timeit.timeit(rosemans_wrapped, number=100000)
timings['prems'] = timeit.timeit(prems_wrapped, number=100000)
# output results
print(timings)
{'yatus': 0.171220442, 'rosemans': 0.153767728, 'prems': 0.22808025399999993}
Roseman 的解决方案是最快的,谢谢。
【问题讨论】:
-
这是对每个键的
dict理解,并使用list理解来构建每个值。你被困在哪里了?显示问题代码,而不是让别人为你写。 -
嗨@Prune 我没有被卡住,而是寻求有关优化的反馈。显示了解决方案,如何在速度、内存使用等方面进行改进。
标签: python list dictionary optimization tuples