简体   繁体   English

基于dicts内部值的所有可能的dicts组合

[英]all possible combinations of dicts based on values inside dicts

I want to generate all possible ways of using dicts, based on the values in them. 我想根据其中的值生成使用dicts的所有可能方法。 To explain in code, I have: 为了在代码中解释,我有:

a = {'name' : 'a', 'items': 3}
b = {'name' : 'b', 'items': 4}
c = {'name' : 'c', 'items': 5}

I want to be able to pick (say) exactly 7 items from these dicts, and all the possible ways I could do it in. 我希望能够从这些词汇中挑选出(确切地说)7个项目,以及我能够做到的所有可行方法。

So: 所以:

x = itertools.product(range(a['items']), range(b['items']), range(c['items']))
y = itertools.ifilter(lambda i: sum(i)==7, x)

would give me: 会给我:

(0, 3, 4)
(1, 2, 4)
(1, 3, 3)
...

What I'd really like is: 我真正喜欢的是:

({'name' : 'a', 'picked': 0}, {'name': 'b', 'picked': 3}, {'name': 'c', 'picked': 4})
({'name' : 'a', 'picked': 1}, {'name': 'b', 'picked': 2}, {'name': 'c', 'picked': 4})
({'name' : 'a', 'picked': 1}, {'name': 'b', 'picked': 3}, {'name': 'c', 'picked': 3})
....

Any ideas on how to do this, cleanly? 关于如何做到这一点的任何想法,干净利落?

Here it is 这里是

import itertools
import operator

a = {'name' : 'a', 'items': 3}
b = {'name' : 'b', 'items': 4}
c = {'name' : 'c', 'items': 5}

dcts = [a,b,c]

x = itertools.product(range(a['items']), range(b['items']), range(c['items']))
y = itertools.ifilter(lambda i: sum(i)==7, x)
z = (tuple([[dct, operator.setitem(dct, 'picked', vval)][0] \
       for dct,vval in zip(dcts, val)]) for val in y)
for zz in z:
    print zz

You can modify it to create copies of dictionaries. 您可以修改它以创建字典副本。 If you need a new dict instance on every iteration, you can change z line to 如果在每次迭代时都需要新的dict实例,则可以将z行更改为

z = (tuple([[dct, operator.setitem(dct, 'picked', vval)][0] \
      for dct,vval in zip(map(dict,dcts), val)]) for val in y)

easy way is to generate new dicts: 简单的方法是生成新的dicts:

names = [x['name'] for x in  [a,b,c]]
ziped = map(lambda x: zip(names, x), y)
maped = map(lambda el: [{'name': name, 'picked': count} for name, count in el],
            ziped) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM