使用python映射将元组中的func类型应用于字符串列表
我有一个所有字符串的“tokens”列表和一个元组列表(fieldname,fieldtype) 比如说使用python映射将元组中的func类型应用于字符串列表,python,list,function,dictionary,Python,List,Function,Dictionary,我有一个所有字符串的“tokens”列表和一个元组列表(fieldname,fieldtype) 比如说 ds = ['1','1','1','1','1'] fs = [('type',str),('value',int),('hidden',bool),('length',int),('pieces',str) 我想做一个dict v,它的形式如下 v = {'type':'1','value',1,'hidden':True,'length':1,'pieces','1') 我目前的效
ds = ['1','1','1','1','1']
fs = [('type',str),('value',int),('hidden',bool),('length',int),('pieces',str)
我想做一个dict v,它的形式如下
v = {'type':'1','value',1,'hidden':True,'length':1,'pieces','1')
我目前的效率非常低(我将元组中的func类型映射到列表中的元素,一次映射一个)
我怎样才能使这篇文章高效易读?我尝试过lambdas等。如果这是一次性操作,我会手动执行,但有多个元组列表,其中一些有50个元素长。您可以修改列表并将fs
中定义的函数应用于相应的ds
值:
>>> ds = ['1','1','1','1','1']
>>> fs = [('type',str),('value',int),('hidden',bool),('length',int),('pieces',str)]
>>> {key: f(value) for (key, f), value in zip(fs, ds)}
{'hidden': True, 'type': '1', 'length': 1, 'value': 1, 'pieces': '1'}
我的想法大致如下:
>>> items = iter(ds)
>>> v = {a: b(next(items)) for a, b in fs}
>>> v
{'type': '1', 'hidden': True, 'pieces': '1', 'length': 1, 'value': 1}
这就是我可能会做的。我的想法(不太可读):
感谢所有人,因为下面的答案如此迅速,似乎是最有效的,甚至从来没有想过听写理解。@dvp它是最有效的,因为您一次只在内存中保存一个项目,但是使用
zip
您不必要地重复了两次。很高兴我能帮忙!
>>> items = iter(ds)
>>> v = {a: b(next(items)) for a, b in fs}
>>> v
{'type': '1', 'hidden': True, 'pieces': '1', 'length': 1, 'value': 1}
>>> v = {t[0]:t[1](ds[i]) for i,t in enumerate(fs)}
>>> v
{'hidden': True, 'type': '1', 'length': 1, 'value': 1, 'pieces': '1'}