Python - check if a letter is in a list
如果字母(字符串)在列表中,查找字母(['o'、['hello'、'c'、'bye'),如果不返回false,则返回true。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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)) |
它确实返回"真的",但我不确定这是否是正确的方法。也许有更好的方法?在第二个elif语句中,如果第一个元素不包含字母,那么python是否会遍历列表中的所有元素?函数必须是递归的。
我认为最可能的方法是使用
1 2 | def find_letter(letter, lst): return any(letter in word for word in lst) |
这样做的好处是,它迭代
如果
因为您需要递归版本:
短版
1 2 3 | 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:])) |
。
更明确的版本
1 2 3 4 5 | 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 |
更明确的版本
1 2 3 4 5 6 7 | 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 |
。
请注意,我遗漏了几个
这是你的错误
1 2 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' |
所以在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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) |
。
刚意识到OP只想检查字符串您可以这样定义一个函数并递归地匹配列表中的字符串:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
。
希望这能解决你的问题。
你想找到会员
请参阅此代码以解决您的问题。假设
1 2 3 4 5 6 | 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 |
号
输出:
1 2 3 | list1[0]: physics list2[1:5]: [2, 3, 4, 5] True |