2013-12-21 48 views
3

设L是字符串列表。查找并在Python中查找下一个

下面是我用在列表中找到字符串texttofind代码L.

texttofind = 'Bonjour' 
for s in L: 
    if texttofind in s: 
     print 'Found!' 
     print s 
     break 

你会怎么做一个查找下一个功能?我是否需要存储以前找到的字符串的索引?

回答

4

巨大列表的一种方法是使用生成器。假设你不知道用户是否需要下一场比赛。

def string_in_list(s, entities): 
    """Return elements of entities that contain given string.""" 
    for e in entities: 
     if s in e: 
      yield e 

huge_list = ['you', 'say', 'hello', 'I', 'say', 'goodbye'] # ... 
matches = string_in_list('y', huge_list) # look for strings with letter 'y' 
next(matches) # first match 
next(matches) # second match 

当你想立即得到所有结果时,其他答案提示列表解析对于短列表很有用。这种方法的好处是,如果你永远不需要第三个结果,那就不会浪费时间找到它。再说一次,这对于大名单来说确实很重要。

更新:如果你想要周期在第一场比赛重新开始,你可以做这样的事情...

def string_in_list(s, entities): 
    idx = 0 
    while idx < len(entities): 
     if s in entities[idx]: 
      yield entities[idx] 
     idx += 1 
     if idx >= len(entities): 
      # restart from the beginning 
      idx = 0 
huge_list = ['you', 'say', 'hello'] 
m = string_in_list('y', huge_list) 
next(m) # you 
next(m) # say 
next(m) # you, again 

对于其他的想法见How to make a repeating generator

另一个更新

它已经年以来我第一次写这个。这里有一个更好的方法使用itertools.cycle

from itertools import cycle # will repeat after end 

# look for s in items of huge_list 
matches = cycle(i for i in huge_list if s in i) 
next(matches) 
+2

可以更简洁地写成'matches =(line for line in L in line in line)' – Eric

+0

请注意['matches.next()'不赞成'next(matches)'](http:/ /stackoverflow.com/q/10414210/102441) – Eric

+0

@Eric,谢谢指出!我想这个函数只有在找到匹配时涉及更复杂的处理时才有用。 – ChrisP

-1

如果存在,将会找到下一个。你可以将它封装在函数中,如果没有则返回None/Empty字符串。

L = ['Hello', 'Hola', 'Bonjour', 'Salam'] 

for l in L: 
    if l == texttofind: 
     print l 
     if L.index(l) >= 0 and L.index(l) < len(L): 
      print L[L.index(l)+1] 
+0

这不查找下一个,这个“的nextS发现” - 它需要在未来_LINE_与比赛 – Eric

3

如果你想找到以L串具有S作为字符串的所有索引,

[i for i in range(0, len(L)) if L[i].find(s) >= 0] 
3

发现在L具有作为子s所有字符串。

[f for f in L if s in f] 
+0

尼斯,我不知道“在”字符串工作的行之后 –