繁体   English   中英

如何遍历单词列表并仅保留 Python 中特定索引处具有特定字母的单词

[英]How to loop through a list of words and only keep the ones that have specific letters at specific indexes in Python

我有一个包含 200,000 个单词的列表、一个包含索引的列表和一个关键字。 index_list不是预定义的,可以是0 to len(keyword)之间的任何大小。

我希望遍历 200,000 个单词,并且仅将包含关键字中字母的单词保留在特定索引处。

例子:

keyword = "BEANS" 
indexList = [0, 3] 

我想在第 0 个索引处保留包含“B”的单词,在第 3 个索引处保留包含“N”的单词。

keyword = "BEANS"
indexList = [0, 1, 2]

我想在第 0 个索引处保留包含“B”的单词,在第一个索引处保留包含“E”的单词,在第二个索引处保留包含“A”的单词。

keyword = "BEANS"
indexList = []

无特定词,全部返回 200,000 个词

眼下,

我有这个代码。 sampleSpace是指 200,000 个单词的列表。

extractedList = []
for i in range(len(indexList)):
    for word in sampleSpace:      
        if (word[indexList[i]] == keyword[indexList[i]]):
            extractedList.append(word)

但是,此代码正在提取在第一个索引处具有值或在第二个索引处具有值或在第 N 个索引处具有值的单词。

我需要单词在特定索引处包含所有字母。

您可以对all使用简单的理解。 对大单词列表中的所有单词进行理解循环,然后使用all检查indexList中的所有索引:

>>> from wordle_solver import wordle_corpus as corpus
>>> keyword = "BEANS"
>>> indexList = [0, 3]
>>> [word for word in corpus if all(keyword[i] == word[i] for i in indexList)]
['BLAND', 'BRUNT', 'BUNNY', 'BLANK', 'BRINE', 'BLEND', 'BLINK', 'BLUNT', 'BEING', 'BRING', 'BRINY', 'BOUND', 'BLOND', 'BURNT', 'BORNE', 'BRAND', 'BRINK', 'BLIND']

首先,改变你的逻辑,让你的循环是for word in sampleSpace 这是因为您想同时考虑每个单词,并查看该单词中的所有相关索引。

接下来,查找all() function ,如果您给它的所有iterable元素都是真值,则返回true 我们如何在这里应用它? 我们想检查是否

all(
    word[index] == keyword[index] for index in indexList
)

所以我们有:

extractedWords = []
for word in sampleSpace:
    if all(word[index] == keyword[index] for index in indexList):
        extractedWords.append(word)

现在因为这个循环只是构造一个列表,我们可以把它写成一个列表推导式,如下所示:

extractedWords = [word 
                    for word in sampleSpace 
                    if all(word[index] == keyword[index] for index in indexList)
                 ]

在执行任何操作之前,您可以使用if条件单独处理空indexList的情况。

def search_keyword_index(sampleSpace, keyword, indexList)
    if not indexList:
        return sampleSpace # or return sampleSpace[:] if you need to return a copy

    return [word for word in sampleSpace if all(word[index] == keyword[index] for index in indexList)]

您可以创建一组 (index,character) 并使用它来快速比较列表中的每个单词:

with open("/usr/share/dict/words") as f:
    words = f.read().upper().split('\n') # 235,887 words

keyword   = "ELEPHANT"
indexList = [0, 3, 5, 7]

letterSet = {(i,keyword[i]) for i in indexList}

for word in words:
    if letterSet.issubset(enumerate(word)):
        print(word)

EGGPLANT
ELEPHANT
ELEPHANTA
ELEPHANTIAC
ELEPHANTIASIC
ELEPHANTIASIS
ELEPHANTIC
ELEPHANTICIDE
ELEPHANTIDAE
ELEPHANTINE
ELEPHANTLIKE
ELEPHANTOID
ELEPHANTOIDAL
ELEPHANTOPUS
ELEPHANTOUS
ELEPHANTRY
EPIPLASTRAL
EPIPLASTRON

您可以使用推导将结果放在列表中:

eligible = [word for word in words if letterSet.issubset(enumerate(word))]

print(len(eligible)) # 18

暂无
暂无

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

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