2014-10-10 57 views
-2

我有一个字符串数组:的Python - 搜索字符串数组

["aaa 1", "aaa 2", "bbb 2", "ccc 3", "ddd 4"] 

我需要寻找在此向量一些字符串,但只有第一部分。例如,我需要从"aaa"开始的字符串的位置(在本例中,这将是0和1)。

我如何做到这一点?

回答

2

您可以使用list comprehensionenumeratestr.split

>>> lst = ["aaa 1", "aaa 2", "bbb 2", "ccc 3", "ddd 4"] 
>>> [x for x,y in enumerate(lst) if y.split()[0] == "aaa"] 
[0, 1] 
>>> 

y.split()[0]将分裂的空间字符串,返回的第一个元素。因此:

if y.split()[0] == "aaa" 

只检查每个字符串的第一部分。然而,如果字符串总是喜欢在你的例子给出的,一个简单的in membership test就足够了:

[x for x,y in enumerate(lst) if "aaa" in y] 
2

我们enumeratestr.startswith

>>> l = ["aaa 1", "aaa 2", "bbb 2", "ccc 3", "ddd 4"] 
>>> print [ind for ind, ele in enumerate(l) if ele.startswith("aaa")] 
[0, 1] 

ind是每个元素在你的列表中的索引,ele是每个元素,所以如果字符串以“aaa”开头,我们将索引添加到列表中

如果没有机会,您将有"aaa"在seco第二串或只使用in上半年的子串的一半将是最有效的

[ind for ind, ele in enumerate(l) if "aaa" in ele] 
0

你有一个清单。为了通过每个项目你可以:

for eachlistitem in listname: 
    if eachlistem[:3] == "ABC": #this only checks first three char of current list item 
     ##do something here like increment a counter 
     ##add counter # to new list to have a list of locations