根据前面的字符串返回子字符串

iKy*_*aki 1 python substring

今天可能有点太多了......但是,好吧.

这个问题让我很困惑.此函数将字符串列表作为参数,并返回每个字符串,该字符串是其前面的字符串的子字符串.所以

  1. ["希望","跳","希望","测试","测试"]将返回['hop']
  2. ["希望","希望","跳","测试","测试"]将返回['hope','hop','test']

请原谅我这里乱七八糟的代码,我还在学习.

def findSubStrs(lst):
'list ==> list, return list of all strings that are substrings of their predecessor in lst'
res = []
for a in lst:
    if len(int(a-1)) > len(lst):
        res = res + [a]
return res
Run Code Online (Sandbox Code Playgroud)

我认为len(int(a-1))可以检查前面的字符串,但我得到错误消息"TypeError:不支持的操作数类型 - :'str'和'int'"唯一的结果我发现有效的是len(a)<3或其他一些int,但这并没有返回我需要的一切.

DSM*_*DSM 5

您可以使用zip以获取要比较的对:

>>> s1 = ["hope", "hop", "hopefully", "test", "testing"]
>>> [b for a,b in zip(s1, s1[1:]) if b in a]
['hop']
>>> s2 = ["hopefully", "hope", "hop", "testing", "test"]
>>> [b for a,b in zip(s2, s2[1:]) if b in a]
['hope', 'hop', 'test']
Run Code Online (Sandbox Code Playgroud)

至于你的代码:

res = []
for a in lst:
    if len(int(a-1)) > len(lst):
        res = res + [a]
return res
Run Code Online (Sandbox Code Playgroud)

这将循环遍历每个元素lst. len(int(a-1))将尝试从字符串中减去1,然后将结果转换为整数,然后取整数的长度,然后将该长度与列表的长度进行比较len(lst).那不是你想要的.(另一个答案已经解释了使用循环和索引执行此操作的正确方法,因此我将停止.)