Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从字符串列表中检索部分匹配项_Python_String_List_Filter - Fatal编程技术网

Python 如何从字符串列表中检索部分匹配项

Python 如何从字符串列表中检索部分匹配项,python,string,list,filter,Python,String,List,Filter,有关在数值列表中检索部分匹配项的方法,请转到: 但是,如果您正在寻找如何检索字符串列表的部分匹配项,您将在下面的答案中找到最佳方法 显示如果列表包含部分匹配某个字符串的元素(例如开始,结束,或包含),如何返回布尔值。但是如何才能返回元素本身,而不是True或False 例子: 在这里,链接问题中的方法将使用以下方法返回True: any(s.startswith(wanted) for s in l) 那么,如何返回元素'threes'? 然后,返回一个布尔值 中的操作符是对成员

有关在数值列表中检索部分匹配项的方法,请转到:


但是,如果您正在寻找如何检索字符串列表的部分匹配项,您将在下面的答案中找到最佳方法

显示如果
列表
包含部分匹配某个字符串的元素(例如
开始
结束
,或
包含
),如何返回
布尔值。但是如何才能返回元素本身,而不是
True
False

例子: 在这里,链接问题中的方法将使用以下方法返回
True

any(s.startswith(wanted) for s in l)
那么,如何返回元素
'threes'

  • 然后,返回一个布尔值
中的
操作符是对成员资格的测试
  • 这可以通过
    列表理解
    过滤器
  • 使用
    列表理解
    ,在
    中使用
    ,是经过测试的最快实现。
  • 如果不是问题,考虑把所有单词映射成小写。
    • l=list(映射(str.lower,l))
  • 过滤器
    • 使用创建一个
      过滤器
      对象,因此
      list()
      用于显示
      列表
      中的所有匹配值
    l=['one','two','threes']
    通缉令=‘三’
    #使用startswith
    结果=列表(过滤器(lambda x:x.startswith(需要),l))
    #用于
    结果=列表(过滤器(λx:x,l中需要)
    打印(结果)
    [out]:
    [‘三’
    
    列表理解
    l=['one','two','threes']
    通缉令=‘三’
    #使用startswith
    结果=[v代表l中的v,如果v.StartWith(需要)]
    #用于
    结果=[v代表l中的v,如果v中需要]
    打印(结果)
    [out]:
    [‘三’
    
    哪种实现更快?
    • 使用
      nltk
    • 带有
      三个“
      • ['three','threefold','threefold','threefoldness','threefoldly','threefoldness','threeling','three Pence','threepenny','threepennyworth','threefoldness','threefoldly','threefoldness','three Penny','threepenny
    从nltk.corpus导入单词
    %timeit列表(筛选器(lambda x:x.startswith(通缉),words.words())
    [out]:
    每个回路47.4 ms±1.9 ms(7次运行的平均值±标准偏差,每个10个回路)
    %timeit列表(过滤器(lambda x:x中需要的单词,words.words())
    [out]:
    每个回路27 ms±1.78 ms(7次运行的平均值±标准偏差,每个10个回路)
    %timeit[v表示v,如果v.startswith(需要),则使用words.words()表示v]
    [out]:
    每个回路34.1 ms±768µs(7次运行的平均值±标准偏差,每个10个回路)
    %timeit[v代表文字中的v.words()(如果需要,在v中)
    [out]:
    每个回路14.5 ms±63.3µs(7次运行的平均值±标准偏差,每个100个回路)
    
    您可以使用for循环查找字符串,而不是返回
    any()函数的结果:

    def find_match(字符串列表,需要):
    对于字符串列表中的字符串:
    如果string.startswith(需要):
    返回字符串
    一无所获
    >>>查找匹配项(['one','twos','threes'],“three”)
    “三”
    
    这对我来说似乎很简单,所以我可能读错了,但您可以通过一个foor循环运行它,并使用if语句

    l = ['ones', 'twos', 'threes']
    wanted = 'three'
    
    def run():
        for s in l:
            if (s.startswith(wanted)):
                return s
    
    print(run())
    
    输出:
    threes

    一个简单、直接的答案:

    test_list = ['one', 'two','threefour']
    r = [s for s in test_list if s.startswith('three')]
    print(r[0] if r else 'nomatch')
    
    结果:

    threefour
    

    不确定在不匹配的情况下要执行什么操作
    r[0]
    正是您要求的匹配项,但如果没有匹配项,则未定义。
    print
    处理这个问题,但您可能希望以不同的方式处理。

    我认为最密切相关的解决方案是使用
    next
    而不是
    任何

    >>> next((s for s in l if s.startswith(wanted)), 'mydefault')
    'threes'
    >>> next((s for s in l if s.startswith('blarg')), 'mydefault')
    'mydefault'
    
    any
    一样,它在找到匹配项后立即停止搜索,只占用O(1)个空间。与列表理解解决方案不同,列表理解解决方案总是处理整个列表并占用O(n)空间

    哦,或者直接按原样使用
    any
    ,但记住最后选中的元素:

    >>> if any((match := s).startswith(wanted) for s in l):
            print(match)
    
    threes
    >>> if any((match := s).startswith('blarg') for s in l):
            print(match)
    
    >>>
    
    另一个变体,仅指定匹配元素:

    >>> if any(s.startswith(wanted) and (match := s) for s in l):
            print(match)
    
    threes
    
    (如果匹配的
    s
    可能是空字符串,则可能需要包含类似
    或True的内容。)

    >>> if any(s.startswith(wanted) and (match := s) for s in l):
            print(match)
    
    threes