簡體   English   中英

給定兩個字符串列表,如何將它們轉換為dict?

[英]Given two list of strings, how can I convert them into a into a dict?

我有以下字符串列表:

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']

如何從他們創建字典:

{
'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']
}
dictionary = dict(zip(labels, content))

各種版本:

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)}

定時

這些已使用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)

最快的

最快的是f3 ,這是@Michael_MacAskill對答案的修改,使用zip而不是使用索引從content提取值。

有趣的是,對@Michael_MacAskill的答案的字典理解並沒有比使用普通for循環的字典表現更好。 也許這種語言的實現者意識到人們在大多數時間仍然堅持使用for循環,並為他們實施了一些性能改進。

大多數Pythonic

如果速度差異不是很關鍵,因為它是該語言的通用用法,那么最有經驗的Python程序員可能會選擇dict(zip(labels, content))選項。

dictionary = {} for i in range(len(content)): dictionary[labels[i]] = content[i] #setting each element in labels list as key and each corresponding index of content list's content as value

也許可以通過字典理解來更有效地完成此操作,但這是一種快速而骯臟的方法:

d = {}                                                                                                                

for i, label in enumerate(labels): 
    d[label] = content[i] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM