【问题标题】:Finding a string in a list python [duplicate]在列表python中查找字符串[重复]
【发布时间】:2014-10-26 17:06:48
【问题描述】:

我有一个单词列表:

words = ["gentleman","woman","boy","girl"]

我正在尝试检查此列表中是否同时出现完整或部分字符串匹配。例如,如果我有字符串

x = "gentleman"

然后我会很容易找到它

if x in words

但是我怎样才能检查部分匹配呢?例如,如果我有

x = "man"

我想将“man”匹配为“gentleman”的一部分。有没有办法同时检查完全匹配和部分匹配?

谢谢

【问题讨论】:

    标签: python string text


    【解决方案1】:

    这很容易做到:

    if any(x in s for s in words):
    

    演示(这两种情况都适用):

    >>> words = ["gentleman", "woman", "boy", "girl"]
    >>> x = "gentleman"
    >>> any(x in s for s in words)
    True
    >>> x = "man"
    >>> any(x in s for s in words)
    True
    

    我在这里做的是遍历words 并检查搜索字符串是否在其中任何一个内。


    编辑:要使其拒绝单字母子字符串,只需进行预检查:

    if len(x) > 1:
        search = any(x in s for s in words)
    else:
        search = False
    

    【讨论】:

    • 我知道这很容易。谢谢亚历克斯。
    • 这似乎是在寻找单字母匹配,是不是只能找到 man 而不是 m?
    • @EnglishGrad 这样做是因为它会找到子字符串,而不管长度如何。为避免这种情况,您可以根据x 的长度进行检查。
    • 它也会匹配“女人”,不能作为“男人”接受
    • @salmanwahed 必须以这种方式完成——'man' 应该为 'gentleman' 而不是 'woman' 的想法在概念上是主观的,因此不适合编程。
    猜你喜欢
    • 2019-11-17
    • 2012-11-26
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2015-08-03
    • 2012-11-07
    相关资源
    最近更新 更多