【问题标题】:Python merge two lists with different lengthsPython合并两个不同长度的列表
【发布时间】:2017-11-30 07:41:19
【问题描述】:

您好,请帮我开发一个遵循的逻辑。

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 次。 请帮忙解决。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • Z = [] for i, a in enumerate(tr_list): Z.append((a, th_list[i % len(th_list)])) 没什么收获

标签: python-2.7 list dictionary merge


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    为了简单,你可以使用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)
    

    【讨论】:

      【解决方案3】:
      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'}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-04
        • 2019-10-16
        • 1970-01-01
        • 2020-06-27
        • 2017-12-24
        • 2017-12-29
        • 1970-01-01
        • 2021-11-19
        相关资源
        最近更新 更多