创建嵌套di的置换

2024-09-21 03:20:37 发布

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

我正在编写一个代码,它应该遍历regu行并创建所有排列(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'}]

。。。你知道吗

j

use = [{'secondary: 'TCP'}]
disc = [{'secondary: 'TCP'}]

。。。你知道吗

use = [{'primary': 'ETH', 'secondary': 'ETH'}
disc = [{'primary': 'ETH'}]

我+1。你知道吗

use = [{'primary': 'ETH', 'secondary': 'ETH'}]
disc = [{'primary': 'ETH'}]

我+2。你知道吗

use = [{'primary': 'ETH', 'secondary': 'ETH'}]
disc = [{'primary': 'ETH', 'secondary': 'ETH'}]

。。。你知道吗

n

use = [{'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP}]
disc = [{'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP}]

Tags: 代码功能协议useprivateregtcpeth
1条回答
网友
1楼 · 发布于 2024-09-21 03:20:37

首先,使用itertools.combinations获取主、次和私有的所有组合,然后使用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'}

相关问题 更多 >

    热门问题