遍历Python默认的di

2024-05-26 22:58:18 发布

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

我在代码中创建了一个默认dict,如下所示:

defaultdict(<class 'list'>, {'month': ['JAN', 'FEB'], 'car': ['baleno', 'santro'], 'measure': ['sales', 'expense']})

cube = 'test'

现在我想通过添加变量cube,以下面的格式打印上面的dict:

['month', 'JAN', 'car', 'baleno', 'measure', 'sales', 'test']

['month', 'JAN', 'car', 'baleno', 'measure','expense', 'test']

['month', 'JAN', 'car', 'santro', 'measure', 'sales', 'test']

['month', 'JAN', 'car', 'santro', 'measure', 'expense', 'test']

['month', 'FEB', 'car', 'baleno', 'measure','sales', 'test']

['month', 'FEB', 'car', 'baleno', 'measure','expense', 'test']

['month', 'FEB', 'car', 'santro', 'measure','sales', 'test']

['month', 'FEB', 'car', 'santro', 'measure','expense', 'test']

我实际上使用了三个循环来实现上述输出,但我希望得到一个整洁的循环。你知道吗

dim=['month','car','measure']
cube='test'
for b in itertools.product(*(k.values())):                                                  
        list1 = list()                                      
        for (f, c) in zip(b, dim):                                                         
            list1.append(c)                                 
            list1.append(f)                                 
        list1.append(cube)                             
        print(list1) 

k是默认的dict

附言:我对Python还不熟悉。就用了几个月。你知道吗


Tags: testcardictjanfeblistmeasuresales
1条回答
网友
1楼 · 发布于 2024-05-26 22:58:18

考虑到输入是一个字典,我认为没有比嵌套for循环更有效的了(注意:itertools.产品相当于for循环)。您可以使用列表理解将其作为一行程序来完成,但这样做效率不会更高,可读性也可能更低。你知道吗

您的实现看起来很好,下面是一个稍微简化的总结:

k = {'month': ['JAN', 'FEB'], 
     'car': ['baleno', 'santro'], 
     'measure': ['sales', 'expense']}

# Grab the keys from the dictionary as opposed to hard-coding them
dim=k.keys()
cube='test'

# cartesian product of each key's set of values
for b in itertools.product(*k.values()):                                                
    list1 = list()
    # extending empty list by (key, value) for specific values in product b                         
    for pair in zip(dim, b):                                                         
        list1.extend(pair)                                 
    list1.append(cube)                             
    print(list1) 

相关问题 更多 >

    热门问题