python - 字符串的子集

标签 python string list subset

我试图获取字符串的每个子集,但不知道该怎么做。如果有人能帮助我那就太好了。

>>> string('ab')
    a, b
>>> string('abc')
    a, b, c, ab, ac, bc,
>>> string('abcd')
    a, b, c, d, ab, bc, cd, da, abc, bcd, cda, dab,

这些都必须在列表中,并且字符串中可能有 n 个字符。程序应该返回所有可以形成的字符串子集。

最佳答案

您可以使用itertools.combinations和这样的列表理解

from itertools import combinations
def myStrings(s):
    return ["".join(item) for i in range(1,len(s)) for item in combinations(s,i)]

print myStrings('ab')
print myStrings('abc')
print myStrings('abcd')

输出

['a', 'b']
['a', 'b', 'c', 'ab', 'ac', 'bc']
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'bc', 'bd', 'cd', 'abc', 'abd', 'acd', 'bcd']

关于python - 字符串的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20161706/

相关文章:

python - 查找 2 个有序列表中未出现在一个列表中的最大元素

python - 我的碰撞函数中的 For 循环从未命中?

python-ldap : what encoding should I use to check password against Microsoft AD?

java - 简单的平均误差,找不到正确的代码

html - css 水平对齐按钮和图标下方的文本

python - 从 python 中的元素列表绘制直方图

python - 使用 Tensorflow 2 的 Keras 功能 API 时传递 `training=true`

python - 无法使用 Python 中的 Mechanize 连接到安全网站

Jquery — 将 URL 正则表达式插入大写句子?

c# - 使用 StringComparer 和 StringBuilder 来搜索字符串