【发布时间】:2013-03-18 01:17:14
【问题描述】:
在 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]
【问题讨论】:
-
提示:
filter。高级提示:filter可以做的任何事情,列表推导可以做。 -
您似乎在要求人们为您编写一些代码。虽然有人可能会这样做,但最好尝试自己编写函数,然后针对您在这样做时遇到的任何问题提出更具体的问题。你试过什么了?您在哪里遇到问题?
-
这是我尝试过的 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搜索
-
我编辑了您的问题以包含您的示例(编辑在队列中,因此可能需要一段时间才能显示给您)但我不得不猜测您是如何缩进的。如果我弄错了,请编辑您的问题。包含一个示例,说明您如何运行函数以及它实际产生的结果与您的预期相反,这也会有所帮助。
-
感谢您抽出宝贵时间改进您的问题。尽管大卫罗宾逊已经给了你一个工作示例,但我试图写一个更完整的解释来说明你如何从你所拥有的东西中获得简洁的列表理解技术,希望这对遇到这个问题的其他人更有启发性未来的问题。
标签: python string list python-3.x