【发布时间】:2013-05-08 12:50:38
【问题描述】:
我想使用元组列表中的值替换列表 (foo) 中的值。每个元组中的第一个值是映射到第一个列表中的值的字段。列表栏中每个元组中的第二个值是我要在列表 foo 中替换的值。
foo = ['a','b','c']
bar = [('a','1'),('b','2'),('c','3')]
预期结果:
result = ['1','2','3']
感谢您的帮助
【问题讨论】:
我想使用元组列表中的值替换列表 (foo) 中的值。每个元组中的第一个值是映射到第一个列表中的值的字段。列表栏中每个元组中的第二个值是我要在列表 foo 中替换的值。
foo = ['a','b','c']
bar = [('a','1'),('b','2'),('c','3')]
预期结果:
result = ['1','2','3']
感谢您的帮助
【问题讨论】:
试试这个:
map(dict(bar).get, foo)
【讨论】:
d = dict(bar) map(d.get, foo) 而不是map(dict(bar… 所以你每次调用函数时都不会创建字典。如果你在一个大循环中运行它可能会带来真正的改进。 不是
dict
dict(bar).get 计算为绑定方法,因此字典只创建一次。
lambda 例如。 map(lambda k: dict(bar).get(k, VAL), foo) 在map
考虑到foo 中的某些项目可能不需要需要替换
例如。
>>> foo = ['a','b','c', 'd']
>>> bar = [('a','1'),('b','2'),('c','3')]
>>> d = dict(bar)
>>> [d.get(x, x) for x in foo]
['1', '2', '3', 'd']
【讨论】:
另一个使用itemgetter的替代方案:
>>> foo = ['a','b','c']
>>> bar = [('a','1'),('b','2'),('c','3')]
>>> from operator import itemgetter
>>> itemgetter(*foo)(dict(bar))
('1', '2', '3')
这给出了tuple,但如果确实需要,这很容易转换。请注意,如果元组是可接受的并且您每次都重复使用相同的 getter,那么这将是一种非常有效的方法:
>>> def mgilson():
... return itemgetter(*foo)(dict(bar))
...
>>> def zwinck():
... return map(dict(bar).get,foo)
...
>>> def alfe():
... b = dict(bar)
... return [b[i] for i in foo]
...
>>> import timeit
>>> timeit.timeit('mgilson()','from __main__ import mgilson')
1.306307077407837
>>> timeit.timeit('zwinck()','from __main__ import zwinck')
1.6275198459625244
>>> timeit.timeit('alfe()','from __main__ import alfe')
1.2801191806793213
>>> def mgilson_mod(getter=itemgetter(*foo)):
... return getter(dict(bar))
...
>>> timeit.timeit('mgilson_mod()','from __main__ import mgilson_mod')
1.1312751770019531
在 Ubuntu Linux 上使用 python2.7.3 64 位完成的测试
【讨论】:
foo*1000 或其他大点看到。考虑到你不应该提前知道foo,这也是一个不公平的模式 IMO。
defaultdict(lambda:default))
非常短的版本:
[ dict(bar)[i] for i in foo ]
考虑在开始时只执行一次dict(bar)。
【讨论】: