根据给定字符串更改列表

1 投票
2 回答
516 浏览
提问于 2025-04-17 19:27

在Python 3中,我想写一个函数 find(string_list, search),这个函数接收一个字符串列表 string_list 和一个单独的字符串 search 作为参数,然后返回所有包含这个搜索字符串的 string_list 中的字符串。

比如说,运行 print(find(['she', 'sells', 'sea', 'shells', 'on', 'the', 'sea-shore'], 'he')) 的时候,应该会打印出:

['she', 'shells', 'the']

这是我到目前为止尝试的:

def find(string_list, search):
    letters = set(search)
    for word in string_list:
        if letters & set(word):
            return word
    return (object in string_list) in search

运行 print(find(['she', 'sells', 'sea', 'shells', 'on', 'the', 'sea-shore'], 'he'))

我期待的结果是 = [she, shells, the]

但我得到的结果是 = [she]

2 个回答

2

你代码中的主要问题是,你只能从一个函数中返回一次值,这样函数就会停止执行。这就是为什么你的函数只返回一个值的原因。

如果你想返回多个值,就必须返回一个容器对象,比如一个 list(列表)或者 set(集合)。如果你使用列表,你的代码可能看起来像这样:

def find(string_list, search):
    letters = set(search)
    result = [] # create an empty list
    for word in string_list:
        if letters & set(word):
            # append the word to the end of the list
            result.append(word)
    return result

这里的 if 测试实际上并没有完全按照你问题的要求来做。因为 set 是一个无序的集合,所以 & 操作只能测试两个集合是否有共同的元素,而不能检查它们是否按照输入的顺序出现。例如:

>>> letters = set("hello")
>>> word = set("olleh")
>>> word & letters
set(['h', 'e', 'l', 'o'])

如你所见,这个操作符返回的是一个集合,里面的元素是两个集合之间的共同元素。由于只要集合里有任何元素,它就被认为是 True,所以这实际上是在测试搜索字符串中的所有字母是否出现在某个项目中,而不是它们是否按给定的顺序一起出现。

一个更好的方法是直接使用 in 操作符来测试字符串,这样可以检查一个字符串是否是另一个字符串的子串,并且是按顺序的:

def find(string_list, search):
    result = []
    for word in string_list:
        if search in word:
            result.append(word)
    return result

因为遍历列表中的每个项目并进行测试的这种模式非常常见,Python 提供了一种更简洁的写法,叫做 列表推导式,可以让你用一个表达式完成整个操作:

def find(string_list, search):
    return [word for word in string_list if search in word]

这段代码的执行效果和之前的例子一样,但写得更简洁。

2

你可以这样做:

def find(string_list, search):
    return [s for s in string_list if search in s]

撰写回答