首页 > 解决方案 > 将特定字符串与单词 python 进行比较

问题描述

说我有一个特定的字符串和一个字符串列表。我想将列表(字符串)中与模式完全相同的所有单词附加到一个新列表中,例如

list of strings = ['string1','string2'...] 
pattern =__letter__letter_ ('_c__ye_' for instance)

我需要在与模式相同的位置添加由相同字母组成的所有字符串,并且具有相同的长度。例如:

new_list = ['aczxyep','zcisyef'...]

我试过这个:

def pattern_word_equality(words,pattern):
list1 = []
for word in words:
    for letter in word:
        if letter in pattern:
            list1.append(word)
return list1

帮助将不胜感激:)

标签: pythonstringlistword

解决方案


这有效:

words = ['aczxyep', 'cxxye', 'zcisyef', 'abcdefg']
pattern = []
for i in range(len(words)):
    if (words[i])[1].lower() == 'c' and (words[i])[4:6].lower() == 'ye':
        pattern.append(words[i])
print(pattern)

您首先定义单词和模式列表。然后你循环words使用len(words). 然后i通过查看第二个字母是否为 c 以及第 5 和第 6 个字母是否为 y 和 e 来确定项目编号是否遵循模式。如果这是真的,那么它将该单词附加到模式上,并在最后将它们全部打印出来。


推荐阅读