【问题标题】:Python list lookup with partial match具有部分匹配的 Python 列表查找
【发布时间】:2023-03-29 13:23:01
【问题描述】:

对于以下列表:

test_list = ['one', 'two','threefour']

我如何知道一个项目是以“三”开头还是以“四”结尾?

例如,不要像这样测试成员资格:

two in test_list

我想这样测试它:

startswith('three') in test_list.

我将如何做到这一点?

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以使用any():

    any(s.startswith('three') for s in test_list)
    

    【讨论】:

    • 这个查找的时间复杂度是多少?它仍然渐近地等效于集合查找吗?
    【解决方案2】:

    您可以使用以下之一:

    >>> [e for e in test_list if e.startswith('three') or e.endswith('four')]
    ['threefour']
    >>> any(e for e in test_list if e.startswith('three') or e.endswith('four'))
    True
    

    【讨论】:

      【解决方案3】:

      http://www.faqs.org/docs/diveintopython/regression_filter.html 应该会有所帮助。

      test_list = ['one', 'two','threefour']
      
      def filtah(x):
        return x.startswith('three') or x.endswith('four')
      
      newlist = filter(filtah, test_list)
      

      【讨论】:

        【解决方案4】:

        如果您正在寻找一种在条件中使用它的方法,您可以这样做:

        if [s for s in test_list if s.startswith('three')]:
          # something here for when an element exists that starts with 'three'.
        

        请注意,这是一个 O(n) 搜索 - 如果它找到一个匹配元素作为第一个条目或任何类似的内容,它不会短路。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-08-12
          • 2018-11-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多