【问题标题】:Python dictionary using 2 different lists with different lengths使用 2 个不同长度的不同列表的 Python 字典
【发布时间】:2020-10-30 20:38:46
【问题描述】:

您好,我尝试使用 zip 函数将这些列表合并到字典中,并且只显示最后一个数据集。有更好的方法吗?

list_values = ['event1','location1','time1','event2','location2','time2','event3','location3','time3','event4','location4','time4']
list_keys = ['event','location','time']

Final desired output dictionary 

output = [{'event':'event1','location':'location1','time':'time1'},{'event':'event2','location':'location2','time':'time2'},{'event':'event3','location':'location3','time':'time3'},{'event':'event4','location':'location4','time':'time4'}]


【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    我们可以使用itertools.cycle 来重复按键。然后我们需要一个列表推导来考虑键列表的长度,然后我们就完成了。

    from itertools import cycle
    
    list_values = ['event1', 'location1', 'time1', 'event2', 'location2', 'time2', 
                   'event3', 'location3', 'time3', 'event4', 'location4', 'time4']
    list_keys = ['event', 'location', 'time']
    
    data = list(zip(cycle(list_keys), list_values))
    result = [dict(data[i:i+len(list_keys)]) for i in range(len(data))[::len(list_keys)] ]
    print(result)
    

    一种更易读的方法,采用"chunks" recipe from this StackOverflow answer

    from itertools import cycle
    
    list_values = ['event1', 'location1', 'time1', 'event2', 'location2', 'time2', 'event3', 'location3', 'time3',
                   'event4', 'location4', 'time4']
    list_keys = ['event', 'location', 'time']
    
    def chunks(lst, n):
        """Yield successive n-sized chunks from lst."""
        for i in range(0, len(lst), n):
            yield lst[i:i + n]
    
    data = list(zip(cycle(list_keys), list_values))
    result = [dict(chunk) for chunk in chunks(data, len(list_keys))]
    print(result)
    

    最后一次修复。如果我们不想通过使用data = list(zip(cycle(list_keys), list_values)) 创建一个列表来耗尽内存,那么有一种方法可以从我们使用zip 获得的可迭代对象中创建块。为此,我们必须导入 islice。我只是列出了对上一个版本的更改。

    from itertools import cycle, islice  # added islice
    
    def chunks(iterable, n):  # new chunk function
        iterable = iter(iterable)
        return iter(lambda: list(islice(iterable, n)), [])
    
    data = zip(cycle(list_keys), list_values)  # no more list
    

    【讨论】:

    • 我喜欢你的第一种方法,但你真的不需要cycle()[dict(zip(list_keys, list_values[i: i + len(list_keys)])) for i in range(0, len(list_values), len(list_keys))]
    • 我应该说我提供的代码将是slightly slower,而不是前两种方法。
    【解决方案2】:

    您必须为输入数据复制足够多次的键:

    import math
    
    list_values = [
        'event1','location1','time1',
        'event2','location2','time2',
        'event3','location3','time3',
        'event4','location4','time4']
    list_keys = ['event','location','time']
    val_count = len(list_values)
    key_count = len(list_keys)
    repl = math.ceil(val_count / key_count)
    
    enough_keys = list_keys * repl
    

    现在你有足够的密钥来压缩这两个列表。我将把“分块”留给你。 :-)

    另一种方法是遍历值:

    for pos, val in enumerate(list_values):
        key = list_keys[pos % len(list_keys)]
    

    这将为您获取与每个值对应的键。

    【讨论】:

      【解决方案3】:

      如果我理解你的正确,你想通过拆分值列表从两个列表中创建多个字典。

      list_values = ['event1','location1','time1','event2','location2','time2','event3','location3','time3','event4','location4','time4']
      list_keys = ['event','location','time']
      
      output=[]
      for i in range(int(len(list_values)/len(list_keys))):
          output+=[dict(zip(list_keys,list_values[i:i+len(list_keys)]))]
      

      【讨论】:

      • 没错,我想从 2 个列表中制作多个字典。感谢您的解决方案和快速响应
      猜你喜欢
      • 1970-01-01
      • 2018-07-03
      • 2017-12-29
      • 1970-01-01
      • 2021-06-10
      • 2017-09-18
      • 2021-10-21
      • 2020-04-01
      • 2020-08-16
      相关资源
      最近更新 更多