更高效/时尚的代码转换数据结构

时间:2014-03-13 15:06:48

标签: python performance python-2.7 coding-style

您是否知道转换此列表的更好/更快的解决方案

['foo1:bar1', 'foo2:bar2', 'foo3:bar3']

进入以下字典

{'col2': ['bar1', 'bar2', 'bar3'], 'col1': ['foo1', 'foo2', 'foo3']}

由于两个for循环,当前版本似乎有点奇怪并且可能很慢。

tuples = ['foo1:bar1', 'foo2:bar2', 'foo3:bar3']
tuples_separated = [one.split(':') for one in tuples]
tidied = {'col1': [], 'col2': []}
for one in tuples_separated:
    tidied['col1'].append(one[0])
    tidied['col2'].append(one[1])

3 个答案:

答案 0 :(得分:6)

使用zip压缩项目?

In [15]: d={}
    ...: vals=zip(*(i.split(':') for i in tuples))
    ...: d['col1'], d['col2']=vals
    ...: print d
{'col2': ('bar1', 'bar2', 'bar3'), 'col1': ('foo1', 'foo2', 'foo3')}

答案 1 :(得分:2)

您可以使用:

dict(zip(('col1', 'col2'), 
     zip(*[item.split(':') for item in x])))

In [93]: x = ['foo1:bar1', 'foo2:bar2', 'foo3:bar3']

In [94]: [item.split(':') for item in x]
Out[94]: [['foo1', 'bar1'], ['foo2', 'bar2'], ['foo3', 'bar3']]

In [95]: zip(*[item.split(':') for item in x])
Out[95]: [('foo1', 'foo2', 'foo3'), ('bar1', 'bar2', 'bar3')]

In [96]: dict(zip(('col1', 'col2'), zip(*[item.split(':') for item in x])))
Out[96]: {'col1': ('foo1', 'foo2', 'foo3'), 'col2': ('bar1', 'bar2', 'bar3')}

答案 2 :(得分:2)

你也可以尝试这个,它适用于任意数量的列:

>>> tuples = ['foo1:bar1', 'foo2:bar2', 'foo3:bar3']
>>>
>>> {'col'+str(i+1):t for i,t in enumerate(zip(*(s.split(':') for s in tuples)))}
{'col2': ('bar1', 'bar2', 'bar3'), 'col1': ('foo1', 'foo2', 'foo3')}