使用2个不同长度的不同列表的Python字典

2024-09-25 08:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我尝试使用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'}]



Tags: eventtimelocationlistevent1time1time2event2
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)]))]

您必须为输入数据复制足够多的密钥:

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

这将获得对应于每个值的键

我们可以使用^{}来重复这些键。然后我们需要一个列表理解,考虑到关键列表的长度,我们就完成了

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得到的iterable中创建块。我们必须为此进口^{}。我只是列出对上一个版本的更改

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

相关问题 更多 >