Skip to main content
 首页 » 编程设计

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

2025年05月04日25freeliver54

今天可能有点太多了..但是嗯。

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

  1. ["hope", "hop", "hopefully", "test", "testing"] 将返回 ['hop']
  2. ["hopefully", "hope", "hop", "testing", "test"] 将返回 ['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 

我认为 len(int(a-1)) 可以检查前面的字符串,但我只收到错误消息“TypeError: unsupported operand type(s) for -: 'str' and 'int'”我发现唯一有效的结果是 len(a) < 3 或其他一些 int,但这并没有返回我需要的一切。

请您参考如下方法:

您可以使用 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'] 

至于你的代码:

res = [] 
for a in lst: 
    if len(int(a-1)) > len(lst): 
        res = res + [a] 
return res 

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