简体   繁体   English

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

[英]Python: comparing list to a string

I want to know how to compare a string to a list. 我想知道如何将字符串与列表进行比较。 For example I have string ' abcdab ' and a list ['ab','bcd','da'] . 例如,我有字符串' abcdab '和列表['ab','bcd','da'] Is there any way to compare all possible list combinations to the string, and avoid overlaping elements. 有什么方法可以将所有可能的列表组合与字符串进行比较,并避免元素重叠。 so that output will be a list of tuples like [('ab','da'),('bcd'),('bcd','ab'),('ab','ab'),('ab'),('da')]. 因此输出将是一个元组列表,例如[('ab','da'),('bcd'),('bcd','ab'),('ab','ab'),('ab'),('da')].

The output should avoid combinations such as ('bcd', 'da') as the character 'd' is repeated in tuple while it appears only once in the string. 输出应避免使用诸如('bcd', 'da')类的组合,因为字符'd'在元组中重复,而在字符串中仅出现一次。

As pointed out in the answer. 如答案中所指出。 The characters in string and list elements, must not be rearranged. 字符串和列表元素中的字符不得重新排列。

One way I tried was to split string elements in to all possible combinations and compare. 我尝试的一种方法是将字符串元素拆分为所有可能的组合并进行比较。 Which was 2^(n-1) n being number of characters. 其中2 ^(n-1)n是字符数。 It was very time consuming. 这非常耗时。

I am new to python programing. 我是python编程的新手。 Thanks in advance. 提前致谢。

all possible list combinations to string, and avoiding overlaping elements 所有可能的列表组合成字符串,并避免元素重叠

Is a combination one or more complete items in its exact, current order in the list that match a pattern or subpattern of the string? 组合中是否有一个或多个完整的项目按照其当前的确切顺序在列表中与字符串的模式或子模式匹配? I believe one of the requirements is to not rearrange the items in the list (ab doesn't get substituted for ba). 我认为其中一项要求是不要重新排列列表中的项目(ab不会替代ba)。 I believe one of the requirements is to not rearrange the characters in the string. 我相信其中一项要求是不要重新排列字符串中的字符。 If the subpattern appears twice, then you want the combinations to reflect two individual copies of the subpattern by themselves as well as a list of with both items of the subpattern with other subpatterns that match too. 如果子图案出现两次,则您希望组合本身反映子图案的两个单独副本,以及该子图案的两个项目以及也匹配的其他子图案的列表。 You want multiple permutations of the matches. 您需要匹配的多个排列。

This little recursive function should do the job: 这个小的递归函数可以完成以下任务:

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

output: 输出:

>>> print matches('abcdab', ['ab','bcd','da'])
[['ab'], ['ab', 'ab'], ['ab', 'da'], ['bcd'], ['bcd', 'ab'], ['da']]

Oops! 哎呀! I somehow missed Rawing's answer. 我莫名其妙地错过了罗林的答案。 Oh well. 那好吧。 :) :)

Here's another recursive solution. 这是另一个递归解决方案。

#! /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()

output 产量

['ab', 'bcd', 'da']
abcdab
[('ab', 'ab'), ('ab',), ('bcd', 'ab'), ('bcd',), ('da', 'ab'), ('da',)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM