【问题标题】:Adding items to list when they already exist and when using for loop当项目已经存在和使用 for 循环时将项目添加到列表中
【发布时间】:2019-04-21 05:59:06
【问题描述】:

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

假设我有以下二维列表:

[

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

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

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

]

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

所以我的结果应该是['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 = ['apple', 'god', 'dog', 'CAT', 'PoP', 'poeT]

我的函数返回:

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

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

【问题讨论】:

  • 欢迎来到 SO!无法重现您的问题,代码会产生正确的输出,假设您修复了缩进错误。
  • 对我来说,返回的列表中有 3 次出现 cat(而不是 4 次),但这是一个不同的问题。
  • 我用适当的例子编辑了我的问题。对困惑感到抱歉。 @ggorlen
  • if word in line_string 只检查line_string 中的word 一次。你需要找到第一个匹配的索引,然后再次从index of the last match + 1开始寻找下一个匹配

标签: python list for-loop


【解决方案1】:

问题是您没有检查该子字符串在字符串中出现的次数。你还需要占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']

【讨论】:

  • 正是我需要的。谢谢。
【解决方案2】:

第一个问题的答案很简单。只需构建一个字符串并每次检查它。如果字符串比目标单词长,则丢失字符串的第一个字母。

outer = [['c', 'a', 't', 'c', 'a', 't'],
         ['a', 'b', 'c', 'a', 't', 'l'],
         ['c', 'a', 't', 'w', 'x', 'y']]

for inner in outer:
  word = ""
  target = "cat"
  t_len = len(target)
  for letter in inner:
    word += letter
    if len(word) > t_len:
      word = word[1:]
    if word in target:
      print(target)

对于第二个问题的答案,您最好只 "".join() 所有字符串并使用正则表达式解析它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-12
    • 2019-02-23
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多