ano*_*non 1 python list-comprehension data-structures python-3.x
我有以下字符串列表:
content = [['a list with a lot of strings and chars 1'], ['a list with a lot of strings and chars 2'], ['a list with a lot of strings and chars 3'], ['a list with a lot of strings and chars 4']]
labels = ['label_1','label_2','label_3','label_4']
Run Code Online (Sandbox Code Playgroud)
如何从他们创建字典:
{
'label_1': ['a list with a lot of strings and chars 1']
'label_2': ['a list with a lot of strings and chars 2']
'label_3': ['a list with a lot of strings and chars 3']
'label_4': ['a list with a lot of strings and chars 4']
}
Run Code Online (Sandbox Code Playgroud)
dictionary = dict(zip(labels, content))
Run Code Online (Sandbox Code Playgroud)
def f1(labels, content):
return dict(zip(labels, content))
def f2(labels, content):
d = {}
for i, label in enumerate(labels):
d[label] = content[i]
return d
def f3(labels, content):
d = {}
for l, c in zip(labels, content):
d[l] = c
return d
def f4(labels, content):
return {l : c for (l, c) in zip(labels, content)}
def f5(labels, content):
dictionary = {}
for i in range(len(content)):
dictionary[labels[i]] = content[i]
return dictionary
def f6(labels, content):
return {l : content[i] for (i, l) in enumerate(labels)}
Run Code Online (Sandbox Code Playgroud)
这些已使用Python 3.6.7进行了测试。请注意,不同版本的Python可能具有不同的性能,因此您可能应该在预期的平台上重新运行基准测试。
In [20]: %timeit f1(labels, content)
637 ns ± 4.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [21]: %timeit f2(labels, content)
474 ns ± 4.44 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [22]: %timeit f3(labels, content)
447 ns ± 2.76 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [23]: %timeit f4(labels, content)
517 ns ± 4.44 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [24]: %timeit f5(labels, content)
529 ns ± 8.04 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %timeit f6(labels, content)
602 ns ± 0.64 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Run Code Online (Sandbox Code Playgroud)
最快的是f3,@Michael_MacAskill对答案的修改,以使用zip而不是使用索引从中提取值content。
有趣的是,对@Michael_MacAskill的答案的字典理解并不比使用普通for循环的字典表现更好。也许这种语言的实现者意识到人们在大多数时间仍然坚持使用for循环,并为他们实施了一些性能改进措施。
dict(zip(labels, content))如果速度差异不是很关键,那么大多数有经验的Python程序员可能会选择该选项,因为这是该语言中的一个常见习惯。