我正在编写一个应该通过reg_lines的代码,并为(1)为每个协议使用哪些行创建所有排列,以及(2)为了检查某些功能而断开哪些行。
reg_lines = {'primary': ['ETH', 'UDP', 'TCP'], 'secondary': ['ETH', 'TCP'], private': ['UDP', 'TCP']}
预期的排列:
1
use = [{'primary':'ETH'}]
disc = [{'primary':'ETH'}]
2
use = [{'primary: 'TCP'}]
disc = [{'primary: 'TCP'}]
...
学家
use = [{'secondary: 'TCP'}]
disc = [{'secondary: 'TCP'}]
...
岛
use = [{'primary': 'ETH', 'secondary': 'ETH'}
disc = [{'primary': 'ETH'}]
i + 1的
use = [{'primary': 'ETH', 'secondary': 'ETH'}]
disc = [{'primary': 'ETH'}]
I + 2。
use = [{'primary': 'ETH', 'secondary': 'ETH'}]
disc = [{'primary': 'ETH', 'secondary': 'ETH'}]
...
<磷>氮use = [{'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP}]
disc = [{'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP}]
答案 0 :(得分:1)
首先,使用itertools.combinations
获取primary,secondary和private的所有组合,然后使用itertools.product
获取这些组合的产品。然后再次使用itertools.combinations
获取disc
词典的所有子集。
from itertools import product, combinations, chain
reg_lines = {'primary': ['ETH', 'UDP', 'TCP'], 'secondary': ['ETH', 'TCP'], 'private': ['UDP', 'TCP']}
def all_combinations(lst):
return chain(*[combinations(lst, i+1) for i in range(len(lst))])
for comb in all_combinations(reg_lines):
for prod in product(*(reg_lines[k] for k in comb)):
use = dict(zip(comb, prod))
print("use", use)
for comb2 in all_combinations(comb):
disc = {k: use[k] for k in comb2}
print("disc", disc)
输出:
use {'primary': 'ETH'}
disc {'primary': 'ETH'}
use {'primary': 'UDP'}
disc {'primary': 'UDP'}
... many many more ...
use {'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}
disc {'primary': 'TCP'}
disc {'secondary': 'TCP'}
disc {'private': 'TCP'}
disc {'primary': 'TCP', 'secondary': 'TCP'}
disc {'primary': 'TCP', 'private': 'TCP'}
disc {'secondary': 'TCP', 'private': 'TCP'}
disc {'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}