我有一个问题:编写一个函数,该函数以列表和字符串作为参数,并根据字符串中的所有字母是否出现在列表中的某个位置返回一个布尔值。这是我到目前为止所拥有的。
def findLetters(myList, myString):
for letter in myString:
if letter in myList:
return True
return False发布于 2017-09-26 08:56:59
这是一个基本的解决方案,它更接近于你已经开始的:
def findLetters(myList, myString):
found_all = False
for s in myString: # check each letter in the string
if s in myList: # see if it is in the list
found_all = True # keep going if found
else:
found_all = False # otherwise set `found` to False
break # and break out of the loop
return found_all # return the result
result = findLetters(['a', 'l', 'i', 's', 't'], 'mlist')
# 'm' is not in the list
print result # False
# all letters in the string are in the list;
# ignores any extra characters in the list that are not in the string
result = findLetters(['a', 'l', 'i', 's', 't', 'p'], 'alist')
print result # True 发布于 2017-09-26 08:47:23
如果myString中有任何字母与myString中的所有字母匹配,则返回True。也可以反过来做,如果myString中有任何字母不匹配,则返回False
def findLetters(myList, myString):
for letter in myString:
if letter not in myList:
return False
return True或者使用内置函数all
def findLetters(myList, myString):
return all(letter in myList for letter in myString)发布于 2017-09-26 08:50:00
您可以使用lambda映射所有字母,这将为my_string中的所有字母创建一个布尔值列表。
如果l列表中的所有值都为True,则函数all返回true。
def find_letters(my_list, my_string):
l = map(lambda x: x in my_list, my_string)
return all(l)
print(find_letters(['a', 'b', 'c'], 'cab'))https://stackoverflow.com/questions/46416137
复制相似问题