1

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

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

  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'” The only result我发现工作是 len(a) < 3 或其他一些 int,但这并没有返回我需要的一切。

4

2 回答 2

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']

至于你的代码:

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

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

于 2013-02-04T05:06:26.543 回答
2

怎么样

print [my_list[i] for i in range(1,len(my_list)) if my_list[i] in my_list[i-1]]

例如

>>> def findSubStrs(my_list):
...     return [my_list[i] for i in range(1,len(my_list)) if my_list[i] in my_list[i-1]]
>>> findSubStrs(["hope", "hop", "hopefully", "test", "testing"] )
['hop']
>>> findSubStrs(["hopefully", "hope", "hop", "testing", "test"])
['hope', 'hop', 'test']

要在没有列表理解的情况下执行此操作,您只需使用一个简单的循环

for i in range(1,len(my_list)):
    if my_list[i] in my_list[i-1]:
        print my_list[i]
于 2013-02-04T05:02:39.803 回答