gpt4 book ai didi

python - 当项目已存在以及使用 for 循环时将其添加到列表中

转载 作者:行者123 更新时间:2023-11-28 21:34:22 25 4
gpt4 key购买 nike

这是一个关于列表和 for 循环的非常简单的问题。

假设我有以下二维列表:

[

['c', 'a', 't', 'c', 'a', 't']

['a', 'b', 'c', 'a', 't, 'l']

['c', 'a', 't', 'w', 'x', 'y']

]

我想使用 for 循环迭代列表,每次检查单词“cat”是否在列表中。 如果是的话,我想每次出现时都将其添加到列表中。

所以我的结果应该是['cat', 'cat', 'cat, 'cat']

我的函数接收一个单词列表和一个给定的矩阵(包含字母列表的二维列表)。我的代码是:

def search_for_words(word_list, matrix):
results = []
for word in word_list:
for line in matrix:
line_string = ''.join(line)
if word in line_string:
results.append(word)
return results

如果 cat 在单词列表中,它只会返回“cat”。

我知道我可能只需要另一个 if 语句,但我可以弄清楚。

提前致谢。

编辑:

我举了一个错误的例子。

考虑一下:

matrix = [['a', 'p', 'p', 'l', 'e'], 
['a', 'g', 'o', 'd', 'o'],
['n', 'n', 'e', 'r', 't'],
['g', 'a', 'T', 'A', 'C'],
['m', 'i', 'c', 's', 'r'],
['P', 'o', 'P', 'o', 'P']]

word_list = ['苹果', '上帝', '狗', '猫', 'PoP', 'poeT]

我的函数返回:

['苹果', '上帝', 'PoP']

当我期望它返回“PoP”两次时,因为它在底部列表中出现两次。

最佳答案

问题是您没有检查该子字符串在字符串中出现了多少次。您还需要考虑 overlapping matches :

import re

def search_for_words(word_list, matrix):
results = []
for word in word_list:
for line in matrix:
line_string = ''.join(line)
# find all overlapping matches of word in line_string
matches = re.findall(r'(?=(' + word + '))', line_string)
results.extend(matches)
return results

如果我们在您的第二个矩阵上运行它:

m = [['a', 'p', 'p', 'l', 'e'], 
['a', 'g', 'o', 'd', 'o'],
['n', 'n', 'e', 'r', 't'],
['g', 'a', 'T', 'A', 'C'],
['m', 'i', 'c', 's', 'r'],
['P', 'o', 'P', 'o', 'P']]

word_list = ['apple', 'god', 'dog', 'CAT', 'PoP', 'poeT']

print(search_for_words(word_list, m))

我们看到以下输出:

['apple', 'god', 'PoP', 'PoP']

关于python - 当项目已存在以及使用 for 循环时将其添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com