【问题标题】:Search an array in Python在 Python 中搜索数组
【发布时间】:2021-01-29 16:36:46
【问题描述】:

我有一个看起来像这样的数组

Arr = ["Jackson", "Greg", "Leon", "Jay", Leia]

我需要像这样过滤它:

Input: Ja
Output: Jackson, Jay

Input: Jack
Output: Jackson

Input: e
Output: Greg, Leon, Leia

Input: Le
Output: Leon, Leia

Input: Leia
Output: Leia

我试过了:

for each in KeyWord:
    search = each + '+'
    output = []
    for i in Arr:
        if(re.findall(each, i)):
            output.append(i)
            cock2 = "Search Results:\n===========\n"
            for x in output:
              Arr += x + "\n"

其中 Arr 包含名称列表。

这个算法将返回的一个例子是

Input: Leia
Output: Leon, Leia

【问题讨论】:

  • 提示:(1)您的搜索修改了您的原始列表(Arr),这可能不是您想要的。 (无论如何它都应该失败,因为你试图连接一个列表和一个字符串)(2)你可以使用in来检查一个字符串是否包含另一个字符串
  • 这能回答你的问题吗? Filtering a list of strings based on contents

标签: python arrays search


【解决方案1】:

您最好使用运算符in 而不是正则表达式。

# Finding all words in Arr that matches KeyWord
output = []
for word in Arr:
    if KeyWord in word:
        output.append(word)

或者,

output = [word for word in Arr if Keyword in word]

如果您仍想使用正则表达式,请查看https://pythonexamples.org/python-re-findall/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2021-06-22
    • 1970-01-01
    • 2014-04-26
    相关资源
    最近更新 更多