2011-01-30 56 views
329

內的字符串我有一個列表:檢查Python列表項包含另一個字符串

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] 

,並希望搜索包含字符串'abc'項目。我怎樣才能做到這一點?

if 'abc' in my_list: 

會檢查是否存在在列表中'abc'但它的'abc-123''abc-456'的一部分,'abc'並不單獨存在。那麼如何獲得包含'abc'的所有物品?

+11

要檢查相反的(如果一個字符串包含多個字符串中的一個):http://stackoverflow.com/a/6531704/2436175 – Antonio 2014-11-18 10:48:40

回答

555

如果你只是要檢查的abc在列表中的任何字符串的存在,你可以嘗試

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] 
if any("abc" in s for s in some_list): 
    # whatever 

如果你真的想要得到包含abc所有項目,使用

matching = [s for s in some_list if "abc" in s] 
+0

我要檢查是否一個項目是由6個元素組成的數組。如果「如果」做得更快或是否一樣? – 2013-03-10 00:11:39

+19

@OlivierPons,只要`myitem in myarray:` – alldayremix 2013-03-21 15:26:10

+5

另一種獲取所有包含子字符串'abc'的字符串的方法:`filter(元素中的lambda元素:'abc',some_list)` – hangtwenty 2013-05-31 20:10:24

9
x = 'aaa' 
L = ['aaa-12', 'bbbaaa', 'cccaa'] 
res = [y for y in L if x in y] 
6
any('abc' in item for item in mylist) 
61

使用filter獲得在該具備的要素abc

>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] 
>>> print filter(lambda x: 'abc' in x, lst) 
['abc-123', 'abc-456'] 

您還可以使用列表理解。

>>> [x for x in lst if 'abc' in x] 

順便說一句,不要用這個詞list作爲變量名,因爲它已被用於list類型。

8
for item in my_list: 
    if item.find("abc") != -1: 
     print item 
19

這是一個很老的問題,但我提供這個答案,因爲以前的答案並不在列表中不串(或某種迭代的對象)的項目應付。這些項目會導致整個列表理解失敗,並有例外。

跳過非迭代的項目與列表中這樣的項目要優雅地處理,使用以下命令:

[el for el in lst if isinstance(el, collections.Iterable) and (st in el)] 

那麼,這樣的名單:

lst = [None, 'abc-123', 'def-456', 'ghi-789', 'abc-456', 123] 
st = 'abc' 

你仍然會得到匹配項(['abc-123', 'abc-456']

可迭代的測試可能不是最好的。從這裏得到它:In Python, how do I determine if an object is iterable?

37

就扔了這一點還有:如果你碰巧需要來匹配多個字符串,例如abcdef,你可以把組合兩個list解析如下:

matchers = ['abc','def'] 
matching = [s for s in my_list if any(xs in s for xs in matchers)] 

輸出:

['abc-123', 'def-456', 'abc-456'] 
0

從我的知識,在 'For' 語句總是消耗時間。

當列表長度增長時,執行時間也會增加。

我認爲,用'is'語句在字符串中搜索子字符串要快一點。

In [1]: t = ["abc_%s" % number for number in range(10000)] 

In [2]: %timeit any("9999" in string for string in t) 
1000 loops, best of 3: 420 µs per loop 

In [3]: %timeit "9999" in ",".join(t) 
10000 loops, best of 3: 103 µs per loop 

但是,我同意any語句更具可讀性。

14

這是最簡單的辦法:

if 'abc' in str(my_list): 
相關問題