【问题标题】:get occurrence of all substring of matching characters from string从字符串中获取匹配字符的所有子字符串的出现
【发布时间】:2021-04-29 18:15:41
【问题描述】:

例如在字符串'abca'中找到包含'a'、'b'、'c'的子字符串,答案应该是'abc'、'abca'、'bca'

下面的代码是我所做的,但有没有比执行 2 个 for 循环更好的 Pythonic 方式?

另一个例子'abcabc' 计数应为 10

def test(x):
    counter = 0
    for i in range(0, len(x)):
        for j in range(i, len(x)+1):
            if len((x[i:j]))>2:
                print(x[i:j])
                counter +=1

    print(counter)
test('abca')

【问题讨论】:

标签: python python-3.x python-2.7


【解决方案1】:

你可以用列表理解来浓缩它:

s = 'abcabc'
substrings = [s[b:e] for b in range(len(s)-2) for e in range(b+3, len(s)+1)]
substrings, len(substrings)
# (['abc', 'abca', 'abcab', 'abcabc', 'bca', 'bcab', 'bcabc', 'cab', 'cabc', 'abc'], 10)

【讨论】:

    【解决方案2】:

    您可以从itertools 使用combinations

    from itertools import combinations
    
    string = "abca"
    
    result = [string[x:y] for x, y in combinations(range(len(string) + 1), r = 2)]
    result = [item for item in result if 'a' in item and 'b' in item and 'c' in item]
    

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 2021-03-30
      • 2015-10-14
      • 2012-07-18
      • 2014-08-07
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多