得到一组"STRINGS"的可能组合. - PYTHON [英] Getting possible combinations of a set of "STRINGS" - PYTHON

查看:44
本文介绍了得到一组"STRINGS"的可能组合. - PYTHON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为获得一组"字符"的可能组合,语法为:

For getting possible combinations of set of "characters", syntax would be:

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

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

What about getting possible combinations of set of "STRINGS" for example :

'A1X2','B1','C19'

'A1X2','B1','C19'

输出应为: ['A1X2B1', 'A1X2C19', 'B1C19']

output should be: ['A1X2B1', 'A1X2C19', 'B1C19']

推荐答案

只需传递strings即可. combinations而不是对"ABC"的每个字符进行迭代,而是对strings列表中包含的字符串进行迭代.并且join的行为相同(Python中的字符和字符串之间没有区别,字符只是大小为1的字符串)

just pass strings instead. Instead of iterating on each char of "ABC", combinations iterates on the strings contained in the strings list. And join acts the same (there is no difference between a character and a string in python, characters are just strings of size 1)

strings = ['A1X2','B1','C19']

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

结果:

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

这篇关于得到一组"STRINGS"的可能组合. - PYTHON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆