[英]Trouble getting list of words given a list of available letters for each character (Python)
I have a list of words that I would like to go through and remove any that don't fit my criteria.我有一个单词列表,我想通过 go 并删除任何不符合我标准的单词。
The criteria is a list of lists of letters that are possible for each character.条件是每个字符可能的字母列表的列表。
letters = [['l','e'],['a','b','c'],['d','e','f']]
words = ['lab','lad','ebf','tem','abe','dan','lce']
The function I have written to try and solve this is:我写的 function 试图解决这个问题是:
def calc_words(letters,words):
for w in words:
for i in range(len(letters)):
if w in words:
for j in letters[i]:
if w in words:
if j != w[i]:
words.remove(w)
return words
The output when I run the function calc_words(letters,words)
should be ['lad', 'ebf', 'lce']
but is instead ['lad', 'tem', 'dan']
当我运行 function 时,output calc_words(letters,words)
应该是['lad', 'ebf', 'lce']
而是['lad', 'tem', 'dan']
I can't figure out what is going on.我不知道发生了什么。 I'm relatively new to Python, so if someone either knows what is going wrong with my function, or knows a different way to go about this, I would appreciate any input.我对 Python 比较陌生,所以如果有人知道我的 function 出了什么问题,或者知道 go 的不同方法,我将不胜感激。
In general, it's good to avoid using one-letter variable names and reduce nesting as much as possible.一般来说,最好避免使用单字母变量名并尽可能减少嵌套。 Here's two implementations of calc_words()
that should suit your needs:这是calc_words()
的两个实现,应该满足您的需求:
letters = [['l','e'],['a','b','c'],['d','e','f']]
words = ['lab','lad','ebf','tem','abe','dan','lce']
def calc_words(letters, words):
# Iterate over each word.
# Assume that a word should be in the result
# until we reach a letter that violates the
# constraint set by the letters list.
result = []
for word in words:
all_letters_match = True
for index, letter in enumerate(word):
if letter not in letters[index]:
all_letters_match = False
break
if all_letters_match:
result.append(word)
return result
# Prints "['lad', 'ebf', 'lce']".
print(calc_words(letters, words))
There is a comment in the first definition that describes how it works.第一个定义中有一条注释描述了它是如何工作的。 This is similar to your implementation, with some nesting removed and some improved naming (eg the if w in words
check aren't necessary, because in each iteration of w
, w
takes on the value of an element from words
).这与您的实现类似,删除了一些嵌套并改进了命名(例如if w in words
检查不是必需的,因为在w
w
从words
中获取元素的值)。 I've tried to keep this solution as close to your original code.我试图让这个解决方案尽可能接近你的原始代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.