在Python中用字符串对后迭代

时间:2018-01-07 16:53:12

标签: python string python-3.x iteration

这是组合/置换器生成器函数,它使用任意数量的列表,其中包含值和任意长度的模板字符串。生成器创建相应的列表,其中包含与模板字符串匹配的值的组合/排列。 答案是由一位同事在这里给出的:https://www.ripstech.com/security-vulnerability-database/

from itertools import permutations, combinations, product

def groups(sources, template, mode='P'):
    func = permutations if mode == 'P' else combinations
    keys = sources.keys()
    combos = [func(sources[k], template.count(k)) for k in keys]
    for t in product(*combos):
        d = {k: iter(v) for k, v in zip(keys, t)}
        yield [next(d[k]) for k in template]

# tests

sources = {
    'a': [0, 1, 2],
    'b': [3, 4, 5],
    'c': [6, 7, 8],
}

templates = 'aa', 'abc', 'abba', 'cab'

for template in templates:
    print('\ntemplate', template)
    for i, t in enumerate(groups(sources, template, mode='C'), 1):
        print(i, t)

输出:

template aa
1 [0, 1]
2 [0, 2]
3 [1, 2]

template abc
1 [0, 3, 6]
2 [0, 3, 7]
3 [0, 3, 8]
4 [0, 4, 6]
5 [0, 4, 7]
6 [0, 4, 8]
7 [0, 5, 6]
8 [0, 5, 7]
9 [0, 5, 8]
10 [1, 3, 6]
11 [1, 3, 7]
12 [1, 3, 8]
13 [1, 4, 6]
14 [1, 4, 7]
15 [1, 4, 8]
16 [1, 5, 6]
17 [1, 5, 7]
18 [1, 5, 8]
19 [2, 3, 6]
20 [2, 3, 7]
21 [2, 3, 8]
22 [2, 4, 6]
23 [2, 4, 7]
24 [2, 4, 8]
25 [2, 5, 6]
26 [2, 5, 7]
27 [2, 5, 8]

template abba
1 [0, 3, 4, 1]
2 [0, 3, 5, 1]
3 [0, 4, 5, 1]
4 [0, 3, 4, 2]
5 [0, 3, 5, 2]
6 [0, 4, 5, 2]
7 [1, 3, 4, 2]
8 [1, 3, 5, 2]
9 [1, 4, 5, 2]

template cab
1 [6, 0, 3]
2 [7, 0, 3]
3 [8, 0, 3]
4 [6, 0, 4]
5 [7, 0, 4]
6 [8, 0, 4]
7 [6, 0, 5]
8 [7, 0, 5]
9 [8, 0, 5]
10 [6, 1, 3]
11 [7, 1, 3]
12 [8, 1, 3]
13 [6, 1, 4]
14 [7, 1, 4]
15 [8, 1, 4]
16 [6, 1, 5]
17 [7, 1, 5]
18 [8, 1, 5]
19 [6, 2, 3]
20 [7, 2, 3]
21 [8, 2, 3]
22 [6, 2, 4]
23 [7, 2, 4]
24 [8, 2, 4]
25 [6, 2, 5]
26 [7, 2, 5]
27 [8, 2, 5]

如您所见,生成器支持由单个字符构成的模板字符串。但是,我感兴趣的是如何转换上面的生成器,以支持模板的字符串,例如以这种形式:

sources = {
     'a1' = [0,1,2],
     'a2' = [3,4,5],
     'a3' = [6,7,8],
}

templates = 'a1a2a3'

在我看来,问题在于来自templates的字符串的迭代,其中迭代在各个元素之后运行。但是,在我的情况下,迭代必须遵循给定字符串中的对。怎么办呢?

1 个答案:

答案 0 :(得分:2)

像这样定义模板:

sources = {
    'a1': [0, 1, 2],
    'a2': [3, 4, 5],
    'a3': [6, 7, 8],
}
templates = [['a1', 'a2', 'a3']]

然后它将开箱即用。这样做的原因是python中的字符串实际上只是字符列表,因此不是定义' abc'你可以定义[' a','' c'],这在大多数情况下都是一样的。