【问题标题】:looping through python default dict循环通过python默认字典
【发布时间】:2019-08-11 00:54:50
【问题描述】:

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

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 是默认字典

PS:我是 PYTHON 的新手。才用了几个月。

【问题讨论】:

  • 看看itertools.product
  • 我已经更新了我使用的代码。 @BlueSheepToken 我已经在使用itertools.product,但不确定我是否以正确的方式使用它!
  • 对我来说看起来不错。不幸的是,您无法加快速度,因为它已经优化

标签: python python-3.x


【解决方案1】:

鉴于输入是一个字典,我认为没有比嵌套 for 循环更高效的了(注意:itertools.product 相当于一个 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) 

【讨论】:

  • 感谢优化代码。但是,寻找一些东西来加快这个过程。那个字典k 只是我给你的一个小样本。但是我的真实代码有一个非常大的字典。 itertools.product 中的 for 循环迭代大约 32616937604160 次,我每小时只能解析 150000 条记录。
  • @User1493 正如我所说,对于计算笛卡尔积,在效率方面,除了嵌套 for 循环之外,您无能为力。在此处查看类似的实现:stackoverflow.com/questions/5228158/…stackoverflow.com/questions/52190140/…
  • @User1493 您可能希望考虑将 dict 转换为数据框,例如melt
猜你喜欢
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 2011-06-29
  • 2019-03-28
  • 1970-01-01
相关资源
最近更新 更多