函数查找列表中的子字符串

时间:2014-05-16 23:13:49

标签: python-3.x

我想创建一个以字符串列表作为参数的算法。它打印列表中的每个字符串,该字符串是其前面的字符串。

我想要函数findSubStrs(lst)的输出示例:

findSubStrs(['hopefully','hope','hop','testing','test'])
hope
hop
test

我有什么:

def findSubStrs(lst):

  for word in lst:
      for letter in word:
          print(letter)

2 个答案:

答案 0 :(得分:1)

使用zip将列表中的每个元素与之前的元素进行比较:

def find_substrs(li):
    return [y for x,y in zip(li,li[1:]) if y in x]

find_substrs(['hopefully','hope','hop','testing','test'])
Out[49]: ['hope', 'hop', 'test']

答案 1 :(得分:0)

以下是使用functools.reduce

的解决方案
from functools import reduce

def find_substrings(array):
    def inner(prev, this):
        print(this) if this in prev else None
        return this
    reduce(inner, array)
find_substrings((['hopefully', 'hope', 'hop', 'testing', 'test'])

我可以用两行来完成if / print,但我嫉妒@ rioppi解决方案的简洁:P