Python合并两个不同长度的列表

时间:2017-06-27 09:44:56

标签: 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)

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 = {}
      else:
         k = k + 1

答案 1 :(得分:0)

简单来说,您可以使用zip

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

chunks = [list_2[idx:idx+3] for idx in range(0, len(list_2), 3)]

output = []

for each in chunks:
    output.append(dict(zip(list_1, each)))

print(output)

答案 2 :(得分:0)

from itertools import cycle

list_1 = [1, 2, 3]

list_2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']


def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]


zipped = tuple(zip(cycle(list_1), list_2))
out = list(map(dict, chunks(zipped, len(list_1))))

print(out)

给你:

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