【问题标题】:Getting possible combinations of a set of "STRINGS" - PYTHON获取一组“字符串”的可能组合 - PYTHON
【发布时间】:2017-09-04 15:24:22
【问题描述】:

为了获得一组“字符”的可能组合,语法为:

>>>q=[''.join(p) for p in itertools.combinations('ABC',2)]
>>>q
['AB', 'AC', 'BC']

如何获得一组“STRINGS”的可能组合 例如:

'A1X2','B1','C19'

输出应该是: ['A1X2B1', 'A1X2C19', 'B1C19']

【问题讨论】:

    标签: python string combinations itertools


    【解决方案1】:

    只需传递 strings 即可。 combinations 不是迭代"ABC" 的每个字符,而是迭代strings 列表中包含的字符串。和join 作用相同(python 中字符和字符串没有区别,字符只是大小为 1 的字符串)

    strings = ['A1X2','B1','C19']
    
    q=[''.join(p) for p in itertools.combinations(strings,2)]
    

    结果:

    ['A1X2B1', 'A1X2C19', 'B1C19']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 2012-03-20
      • 2011-05-26
      • 2011-03-13
      相关资源
      最近更新 更多