【问题标题】:Returning substrings depending on preceding string根据前面的字符串返回子字符串
【发布时间】:2013-02-04 05:00:03
【问题描述】:

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

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

  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)

【问题讨论】:

    标签: python substring


    【解决方案1】:

    您可以使用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) 的长度进行比较。那不是你想要的。 (另一个答案已经解释了使用循环和索引的正确方法,所以我会停下来。)

    【讨论】:

    • gj 解释 OP 代码出了什么问题(TBH 很难说该代码是为了解决手头的问题......)
    【解决方案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]
    

    【讨论】:

    • 这实际上工作得很好,谢谢。但是,我将如何编写它以使其不是列表理解形式?我认为在这一点上,我更容易以这种方式真正理解它。
    • 好的,非常感谢。我现在明白了很多。
    • zip 解决方案很好,因为您不必担心索引和列表长度...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2016-08-27
    • 2015-09-18
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多