【问题标题】:What’s the best way to Convert a list to dict in Python2.7在 Python2.7 中将列表转换为 dict 的最佳方法是什么
【发布时间】:2017-05-24 16:53:16
【问题描述】:

我有一个类似的列表:

x = ['user=inci', 'password=1234', 'age=12', 'number=33']

我想将 x 转换为如下的字典:

{'user': 'inci', 'password': 1234, 'age': 12, 'number': 33}

最快的方法是什么?

【问题讨论】:

    标签: python python-2.7 list dictionary type-conversion


    【解决方案1】:

    基准测试

    dictmap 方法 (f1)

    dict(map(lambda i: i.split('='), x))
    

    天真的方法 (f2)

    d = dict()
    for i in x:
        s = x.split("=")
        d[s[0]] = s[1]
    return d
    

    仅限dict (f3)

    dict(item.split('=') for item in x)
    

    比较

    def measure(f, x):
        t0 = time()
        f(x)
        return time() - t0
    
    >>> x = ["{}={}".format(i, i) for i in range(1000000)]
    
    >>> measure(f1, x)
    0.5690059661865234
    
    >>> measure(f2, x)
    0.5518567562103271
    
    >>> measure(f3, x)
    0.5470657348632812
    

    【讨论】:

    • 当列表的长度很大时,Naive 方法更快。但是,当列表长度较小时,“dict(item.split('=') for item in x)”方法比 Naive 方法更快。
    • @nanci 实际上,当列表很大时,最后一种方法(您接受的)仍然更好。
    【解决方案2】:

    你可以用一个简单的衬里做到这一点:

    dict(item.split('=') for item in x)
    

    列表推导(或生成器表达式)通常比使用 maplambda 更快,并且通常被认为更具可读性,请参阅 here

    【讨论】:

      【解决方案3】:

      dict(map(lambda i: i.split('='), x))

      【讨论】:

      • 这个方法比 dict(item.split('=') for item in x) 慢
      猜你喜欢
      • 2016-03-20
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 2016-05-29
      • 2012-02-29
      • 1970-01-01
      相关资源
      最近更新 更多