合并到不同长度的列表以获取字典列表

时间:2017-06-27 11:36:04

标签: python-2.7 list dictionary merge

嗨,请帮我开发一个跟随的逻辑。

list_1 = [1,2,3]
list_2 = [a,b,c,d,e,f,g,h,i]

必需的输出(词典列表):

output = [{1:a,2:b,3:c}, {1:d,2:e,3:f}, {1:g,2:h,3:i}]

我的剧本:

return_list = []
k = 0
temp_dict = {}

for i, value in enumerate(list_2):
    if k <= len(list_1)-1:
        temp_dict[list_1[k]] = value
        if k == len(list_1)-1:
            k = 0
            print temp_dict
            return_list.append(temp_dict)
            print return_list
            print '\n'
        else:
            k = k + 1
print return_list

我的输出:

{1: 'a', 2: 'b', 3: 'c'}
[{1: 'a', 2: 'b', 3: 'c'}]


{1: 'd', 2: 'e', 3: 'f'}
[{1: 'd', 2: 'e', 3: 'f'}, {1: 'd', 2: 'e', 3: 'f'}]


{1: 'g', 2: 'h', 3: 'i'}
[{1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}]


[{1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}, {1: 'g', 2: 'h', 3: 'i'}]

如您所见,temp_dict正确打印,但return_list是最后一次temp_dict 3次。 请帮忙解决。

3 个答案:

答案 0 :(得分:0)

此处的问题是您没有将temp_dict重置为新对象。 当你将它附加到列表时,它仍然保持对dict对象的引用,在下一个循环中更改它之后,它会更改数组上的值,因为它是相同的引用。

如果你重置它应该有效

list_1 = [1,2,3]
list_2 = ['a','b','c','d','e','f','g','h','i']

return_list = []
k = 0
temp_dict = {}

for i, value in enumerate(list_2):
    if k <= len(list_1)-1:
        temp_dict[list_1[k]] = value
        if k == len(list_1)-1:
            k = 0
            print temp_dict
            return_list.append(temp_dict)
            temp_dict = {} # Here is the change
            print return_list
            print '\n'
        else:
            k = k + 1
print return_list

答案 1 :(得分:0)

这应该有效:

list_1 = [1,2,3]
list_2 = ['a','b','c','d','e','f','g','h','i']

output = []

j = 0
for i in range(1, len(list_1) + 1):
    output.append(dict(zip(list_1, list_2[j:i * 3])))
    j = i * 3

print(output)

假设您的第二个列表恰好是第一个列表的3倍。

答案 2 :(得分:0)

def merge_them(list1, list2):
    output = []
    i = 0
    while i < len(list_2):
        output.append(dict(zip(list_1, list_2[i: i + len(list1)])))
        i += len(list1)

    return output

你可以测试一下:

<强> TEST1:

list_1 = [1,2,3]
list_2 = ['a','b','c','d','e','f','g','h','i']
print merge_them(list_1, list_2)

你会得到:

[{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]

<强> TEST2:

list_1 = [1,2,3,]
list_2 = ['a','b','c','d','e']
print merge_them(list_1, list_2)

you will get:

[{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e'}]

<强> TEST3:

list_1 = [1,2,3,4,5,6,7,8]
list_2 = ['a','b','c','d','e']
print merge_them(list_1, list_2)

you will get:

[{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}]
相关问题