【问题标题】:One liner to extract values within list of dictionaries into multiple variables一种将字典列表中的值提取到多个变量中的衬垫
【发布时间】:2022-10-04 18:24:50
【问题描述】:

假设我们有一个结构相似的字典列表,例如:

lst_of_dcts = [
    {
        'a': 1,
        'b': 2,
        'c': 3,
        'd': 4,
    },
    ...
    {
        'a': 10,
        'b': 11,
        'c': 12,
        'd': 13,
    },
    {
        'a': 14,
        'b': 15,
        'c': 16,
        'd': 17,
    }
]

我想提取键列表,例如

as = [d['a'] for d in lst_of_dcts]
bs = [d['b'] for d in lst_of_dcts]
cs = [d['c'] for d in lst_of_dcts]

例如,as == [1, ..., 10, 14]

有没有一种更简洁的方法可以做到这一点,也许在一行中,这可以节省我多次迭代字典列表。

【问题讨论】:

    标签: python


    【解决方案1】:

    这作为一个衬垫工作:

    a,b,c = list(map(list, zip(*[(d['a'], d['b'], d['c']) for d in lst_of_dcts])))

    但是,您牺牲了 1. 可读性和 2. 速度。

    import numpy as np
    import time
    
    n_iter = 10000
    times = []
    for _ in range(n_iter):
        t0 = time.time()
        a,b,c = list(map(list, zip(*[(d['a'], d['b'], d['c']) for d in lst_of_dcts])))
        times.append(time.time() - t0)
    print(np.mean(times))
    
    times = []
    for _ in range(n_iter):
        t0 = time.time()
        a =[d['a'] for d in lst_of_dcts]
        b =[d['b'] for d in lst_of_dcts]
        c =[d['c'] for d in lst_of_dcts]
        times.append(time.time() - t0)
    print(np.mean(times))
    

    时间:

    2.23792e-06s
    1.68469e-06s
    

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 2012-09-11
      • 1970-01-01
      • 2010-09-08
      • 2020-08-04
      相关资源
      最近更新 更多