2017-09-26 66 views
0

我有一個問題,指出:編寫一個函數,它將一個列表和一個字符串作爲參數,並根據字符串中的所有字母是否出現在某處在列表中。這是我到目前爲止。在列表中找到一個字母

def findLetters(myList, myString): 
    for letter in myString: 
     if letter in myList: 
      return True 
    return False 
+0

這將在第一場比賽返回True,如果不是所有的字母都在列表中。 – MrE

+0

請說出您的問題 – pylang

回答

0

如果任何字母匹配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) 
0

您可以使用它創建一個列表中的拉姆達映射所有字母my_string中所有字母的布爾值。

功能all返回true如果在l列表中的所有值ar 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')) 
1

這裏有一個基本的解決方案,它更接近你開始了的事情:

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 
相關問題