Python如何循环列表并使用列表值中的每个2作为参数? [英] Python how to looping a list and use each 2 of the list value as a parameter?

查看:57
本文介绍了Python如何循环列表并使用列表值中的每个2作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个嵌套列表:

 grouped1 ={'LabelStat': { 'Carrier': ['1', '1'],
                           'FormID': ['0201', '0430']},
          
             'McAfee': {'DatDate': 'Not Available',
            '            DatVersion': 'Not Available'}
           }
    
 grouped2 ={'LabelStat': {'Carrier': ['2', '2'],
                          'FormID': ['10201', '10430']},
         'McAfee': {'DatDate': 'Available',
            'DatVersion': 'Available',}
           }

一个函数将合并这两个列表,并且可以正常工作:

And a function will merge these 2 lists and it works:

from collections import defaultdict
import re
def merge(*d):
   v = defaultdict(list)
   for i in d:
      for a, b in i.items():
         v[re.sub('^\s+', '', a)].append(b)
   return {a:merge(*b) if all(isinstance(j, dict) for j in b) 
            else [i for j in b for i in (j if isinstance(j, list) else [j])] 
              for a, b in v.items()}

print(merge(grouped1, grouped2))

此函数的输出为:

om_grouped = {
    'LabelStat': {'Carrier': ['1', '1','2','2'],
                   'FormID': ['0201', '0430','10201', '10430']}
             
    'McAfee': {'DatDate': ['Not Available','Available']
               'DatVersion': ['Not Available','Available']}
    
             }

所以现在字典的数量是固定的,在上面我有2,但是如果数字是动态的,例如我也会有grouped3:

So now the amount of dictionary is fixed, in the above I have 2,but what if the number will be dynamic, for example I will also have grouped3:

grouped3 ={'LabelStat': {'Carrier': ['3', '3'],
                          'FormID': ['102013', '104303']},
         'McAfee': {'DatDate': 'Available3',
            'DatVersion': 'Available3',}
           }

我的问题是如何修改合并功能以使参数动态化?

My question how to modify merge function to make the parameter dynamic?

我试图将所有词典放在一个列表中:

I have tried to put all the dictionary in a list:

dic_list = [grouped1,grouped2,grouped3]

然后使用地图功能:

combin = map(merge,d_list)

print(combin)
for i in combin:
    print(i)

但是输出是:

<map object at 0x000001AC43E7AF40>
{'LabelStat': {'Carrier': ['1', '1'], 'FormID': ['0201', '0430']}, 'McAfee': {'DatDate': ['Not Available'], 'DatVersion': ['Not Available']}}
{'LabelStat': {'Carrier': ['2', '2'], 'FormID': ['10201', '10430']}, 'McAfee': {'DatDate': ['Available'], 'DatVersion': ['Available']}}
{'LabelStat': {'Carrier': ['3', '3'], 'FormID': ['102013', '104303']}, 'McAfee': {'DatDate': ['Available3'], 'DatVersion': ['Available3']}}

推荐答案

只需使用拆包:

r = merge(*dic_list)

输出:

{'LabelStat': {'Carrier': ['1', '1', '2', '2', '3', '3'], 'FormID': ['0201', '0430', '10201', '10430', '102013', '104303']}, 'McAfee': {'DatDate': ['Not Available', 'Available', 'Available3'], 'DatVersion': ['Not Available', 'Available', 'Available3']}}

这篇关于Python如何循环列表并使用列表值中的每个2作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆