簡體   English   中英

Python 列表查找與部分匹配

[英]Python list lookup with partial match

對於以下列表:

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

我如何知道一個項目是以“三”開頭還是以“四”結尾?

例如,不要像這樣測試成員資格:

two in test_list

我想像這樣測試它:

startswith('three') in test_list

我將如何做到這一點?

您可以使用any()

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

您可以使用其中之一:

>>> [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

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)

如果您正在尋找一種在條件中使用它的方法,您可以這樣做:

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

請注意,這是一個 O(n) 搜索 - 如果它找到匹配元素作為第一個條目或沿着這些行的任何內容,它不會短路。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM