【问题标题】:Iterating after pairs in string in Python在Python中的字符串对之后进行迭代
【发布时间】:2018-06-16 18:59:02
【问题描述】:

这是组合/置换器生成器函数,它使用任意数量的带有值的列表和任意长度的模板字符串。生成器使用与模板字符串匹配的值的组合/排列创建相应的列表。 这里的一位同事给出了答案:https://stackoverflow.com/a/48121777/8820330

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 的字符串的迭代,其中迭代在单个元素之后运行。但是,就我而言,迭代必须遵循给定字符串中的对。如何做到这一点?

【问题讨论】:

    标签: python string python-3.x iteration


    【解决方案1】:

    像这样定义你的模板:

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

    然后它就会开箱即用。这样做的原因是 python 中的字符串实际上只是字符列表,因此您可以定义 ['a', 'b', 'c'] 而不是定义 'abc' 并且这在大多数情况下表现相同。

    【讨论】:

    • 呵呵很酷,我在分配迭代的方式中不必要地寻找一些东西 :) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    相关资源
    最近更新 更多