【问题标题】:Python - check if a letter is in a listPython - 检查一个字母是否在列表中
【发布时间】:2014-12-08 21:58:02
【问题描述】:

如果一个字母(字符串)在一个列表中, find_letter(['o', ['hello', 'c', 'bye']), 返回 True,否则返回 False。

def find_letter(lst):

    lst=['o','hello', 1]
    n='o'

    if not lst:          
        return 0

    elif lst[0] == n:
        return True

    elif find_letter(lst[0:]):
        return True

    else: 
        return False


print(find_letter(lst))

它确实返回“True”,但我不确定这是否是正确的方法。也许有更好的方法?在第二个 elif 语句中,如果第一个不包含字母,python 是否会遍历列表中的所有元素?该函数必须是递归的。

【问题讨论】:

  • is python going through all the elements in the list if the first one doesn't contain the letter - 您可以使用print 语句来确认您自己:-)
  • 欢迎使用stackoverflow,你能修复你的缩进吗?
  • list 是 python 中的一种类型,因此它是内置的。不要将其用作变量名,否则您将覆盖现有的 python 类型。
  • 您的递归函数看起来不错,但其中有一个简单的错误。在elif find_letter(lst[0:]) 中,您将相同的列表提供给find_letter 函数。您必须跳过第一个元素(零索引元素)并返回其他元素。您必须正确使用列表切片。
  • @FallenAngel 我试过 (lst[1:)] 和 (lst[:-1]),但都没有奏效。

标签: python string list recursion


【解决方案1】:

我认为最pythonic的方法是使用

def find_letter(letter, lst):
    return any(letter in word for word in lst)

它的美妙之处在于它遍历lst 并在该列表中的单词之一包含letter 时立即返回。此外,它不需要递归。

如果lst 为空,这将返回False 而不是0,虽然(与您的程序不同)但由于False 无论如何都会评估为0(反之亦然),所以这不是一个真正的问题。

【讨论】:

  • 不幸的是,OP 刚刚编辑了他的问题以添加“函数必须是递归的”!
  • @Ben:哦,运气不好。是的,因为它强迫学生在根本不需要递归的例子上学习递归。除非我们正在处理嵌套列表。
【解决方案2】:

因为你需要一个递归版本:

短版

def find_letter(let, lst):
    return (lst or False) and \
           ((isinstance(lst[0], str) and let in lst[0]) or find_letter(let, lst[1:]))

更明确的版本

def find_letter(let, lst):
    if lst:
        e = lst[0]
        return (isinstance(e, str) and let in e) or find_letter(let, lst[1:])
    return False

更明确的版本

def find_letter(let, lst):
    if lst:
        e = lst[0]
        if isinstance(e, str) and let in e:
            return True
        return find_letter(let, lst[1:])
    return False

请注意,我省略了几个else:,因为在return 语句之后它们不是必需的。如果您不想测试字符串中的字母,而只是为了相等,请将let in ... 替换为let == ...

【讨论】:

    【解决方案3】:

    这是你的错误

    def find_letter(lst):  # You receive your list as lst
        lst=['o','hello', 1]  # Opppsss! You override it. It does not matter what you receive with lst above, now its value is ['o','hello', 1]
        n='o'
    

    所以在find_letter(lst[0:]) 中,您使用列表切片,但在lst=['o','hello', 1] 行中,您再次覆盖它,并且始终在列表的第一个元素上执行搜索。

    n = "o"  # you can set this too, but this is optional
    def find_letter(lst):
        # do not set a value to lst in here
    
        if not lst:          
            return 0
    
        elif lst[0] == n:  # You checked first element in here
            return True
    
        elif find_letter(lst[1:]):  # since you checked the first element, skip it and return the orher elements of the list
            return True
    
        else: 
            return False
    
    lst = ['o','hello', 1]
    print find_letter(lst)
    

    【讨论】:

      【解决方案4】:

      您要查找会员资格

      请参考此代码来解决您的问题。 假设

      list1 = ['physics', 'chemistry', 1997, 2000];
      list2 = [1, 2, 3, 4, 5, 6, 7 ];
      
      print "list1[0]: ", list1[0]
      print "list2[1:5]: ", list2[1:5]
      print 3 in list2    
      

      输出:

      list1[0]:  physics
      list2[1:5]:  [2, 3, 4, 5]
      True
      

      【讨论】:

        【解决方案5】:

        刚刚意识到 OP 只想检查 一个字符串 您可以像这样定义一个函数并递归匹配列表中的字符串:

        def plist(lst, n):
            # loop inside the list
            for each in lst:
                # if "each" is also a list (nested), check inside that list, too
                if isinstance(each, list):
                    # this will reuse your "plist" and loop over any nested list again
                    plist(each, n)
                # if n matches any element in the list, return True
                if any(n in each_letter for each_letter in each):
                    return True
            # if after looping over your list + nested list, return False if no match is find
            else:
                return False
        
        >> lst = ['o', ['hello', 'c', 'bye']]
        >> plist(lst, 'o')
        >> True
        >> plist(lst, 'h')
        >> True
        >> plist(lst, 'z')
        >> False
        

        希望这能解决您的问题。

        【讨论】:

          猜你喜欢
          • 2012-04-04
          • 2013-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-08
          • 2016-05-14
          • 1970-01-01
          相关资源
          最近更新 更多