Python:将列表与字符串进行比较

2024-05-13 04:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何比较字符串和列表。 例如 我有字符串“abcdab”和一个列表['ab','bcd','da']。是否有任何方法可以将所有可能的列表组合与字符串进行比较,并避免元素重叠。所以输出将是一个元组列表,如下所示 [('ab','da'),('bcd'),('bcd','ab'),('ab','ab'),('ab'),('da')].

输出应避免组合,如('bcd', 'da'),因为字符“d”在元组中重复,而它在字符串中只出现一次。在

正如答案中指出的那样。字符串和列表元素中的字符不能重新排列。在

我尝试的一种方法是将字符串元素拆分为所有可能的组合并进行比较。2^(n-1)n是字符数。这很费时。在

我是python编程新手。 提前谢谢。在


Tags: 方法字符串答案元素列表ab编程字符
3条回答

这个小递归函数可以完成以下工作:

def matches(string, words, start=-1):
    result= []
    for word in words: # for each word
        pos= start
        while True:
            pos= string.find(word, pos+1) # find the next occurence of the word
            if pos==-1: # if there are no more occurences, continue with the next word
                break

            if [word] not in result: # add the word to the result
                result.append([word])

            # recursively scan the rest of the string
            for match in matches(string, words, pos+len(word)-1):
                match= [word]+match
                if match not in result:
                    result.append(match)
    return result

输出:

^{pr2}$

哎呀!我不知怎的错过了罗文的答案。哦,好吧。:)

这是另一个递归解决方案。在

#! /usr/bin/env python

def find_matches(template, target, output, matches=None):
    if matches is None:
        matches = []

    for s in template:
        newmatches = matches[:]
        if s in target:
            newmatches.append(s)
            #Replace matched string with a null byte so it can't get re-matched
            # and recurse to find more matches.
            find_matches(template, target.replace(s, '\0', 1), output, newmatches)
        else:
            #No (more) matches found; save current matches
            if newmatches:
                output.append(tuple(newmatches))
            return


def main():
    target = 'abcdab'
    template = ['ab','bcd','da']

    print template
    print target

    output = []
    find_matches(template, target, output)
    print output


if __name__ == '__main__':
    main()

输出

^{pr2}$

all possible list combinations to string, and avoiding overlaping elements

一个组合是否是一个或多个完整的项,在列表中的当前顺序与字符串的模式或子模式匹配?我认为其中一个要求是不要重新排列列表中的项目(ab不能代替ba)。我认为其中一个要求是不要重新排列字符串中的字符。如果子模式出现两次,那么您希望组合反映子模式的两个单独副本,以及子模式的两个项目与其他匹配的子模式的列表。你想要多个匹配的排列。在

相关问题 更多 >