我希望使用元组列表中的值替换列表(foo)中的值。每个元组中的第一个值是要映射到第一个列表中的值的字段。在列表bar中,每个元组的第二个值是我想要替换在列表foo中的值。
foo = ['a','b','c']
bar = [('a','1'),('b','2'),('c','3')]
预期结果:
result = ['1','2','3']
感谢您的帮助。
我希望使用元组列表中的值替换列表(foo)中的值。每个元组中的第一个值是要映射到第一个列表中的值的字段。在列表bar中,每个元组的第二个值是我想要替换在列表foo中的值。
foo = ['a','b','c']
bar = [('a','1'),('b','2'),('c','3')]
预期结果:
result = ['1','2','3']
试试这个:
map(dict(bar).get, foo)
[ dict(bar)[i] for i in foo ]
dict(bar)
。itemgetter
的替代方法:>>> foo = ['a','b','c']
>>> bar = [('a','1'),('b','2'),('c','3')]
>>> from operator import itemgetter
>>> itemgetter(*foo)(dict(bar))
('1', '2', '3')
>>> 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
。 - jamylakdefaultdict(lambda: default)
)。 - mgilson考虑到在 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']
dict(bar).get
的计算结果是一个绑定方法,因此字典只会被创建一次。 - chepnerlambda
,例如map(lambda k: dict(bar).get(k, VAL), foo)
在map
中。 - jamylakNone
不同的默认值,可以尝试这样做:map(defaultdict(lambda: 'nothing', bar).__getitem__, foo)
。 - John Zwinck