如何检查某个词是否可以用于 Python 中的另一个词

How to check if a certain word can be used for another word in Python

和平,

f.ex.:

你的单词是 "AAAaaaaa" 并且你想检查你可以用它创建哪些单词与另一个列表相比。

f.ex。在列表中有:

AA

AAH

AAHED

AAHING

AAHS

AAL

AALII

AALIIS

AALS

所以唯一的输出应该是 "AA" 因为你不能在你错过字母的地方创建东西。

到目前为止我得到了这个,但它输出了列表中包含 "A" 的每个单词。

with open("sowpods.txt", "r") as check: #TOWORK WITH
        for line in check.readlines():
                for x in word:
                        for y in line:
                                if x in y:
                                        valid_words.append(line.strip())

我认为你可以采用这样的逻辑:

s= "AAAaaaaa"
list =["AA","AAH", "AAHED","AAHING", "AAHS"]
valid_words=[]

flag = True
for i in range(0,len(list)):
  for j in range (0,len(list[i])):
    if list[i][j] in s :
      continue
    else:
      flag = False
      break
  if flag :
    print (list[i] + " exists")
    valid_words.append(list[i])

你可以使用filter

    word = "ZZAAEE"
    existing = ["AA", "AAH", "ZEZE", "AAHING", "AAHS"]
    valid_words = []

    def cmp_str(exist): # exist is one item in existing list
        copy_word = str(word) # so to not modified the word
        for c in exist:
            idx = copy_word.find(c) # find the index of char in word
            if idx == -1:
                return False
            copy_word = copy_word[:idx] + copy_word[idx+1:] # drop the match character

        return True

    valid_words = list(filter(cmp_str, existing)) # cmp_str is called by the filter function
    print(valid_words)

PS:更新代码,因为字符的位置应该被忽略

In [1]: words = ['ZIZ', 'ZIZZ', 'ZZI']

In [2]: w = "ZZAAI"

In [3]: for word in words:
    ...:     match=False
    ...:     chars = list(word)
    ...:     for i in list(w):
    ...:         if i in chars:
    ...:             match = True
    ...:             chars.remove(i)
    ...:         else:
    ...:             match=False
    ...:     if len(chars) == 0:
    ...:         print(word)
    ...:     elif not set(chars).issubset(list(w)):
    ...:         print(word)