首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在列表中查找字母

在列表中查找字母
EN

Stack Overflow用户
提问于 2017-09-26 08:39:49
回答 3查看 7K关注 0票数 0

我有一个问题:编写一个函数,该函数以列表和字符串作为参数,并根据字符串中的所有字母是否出现在列表中的某个位置返回一个布尔值。这是我到目前为止所拥有的。

代码语言:javascript
复制
def findLetters(myList, myString):
    for letter in myString:
        if letter in myList:
            return True
    return False
EN

回答 3

Stack Overflow用户

发布于 2017-09-26 08:56:59

这是一个基本的解决方案,它更接近于你已经开始的:

代码语言:javascript
复制
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 
票数 1
EN

Stack Overflow用户

发布于 2017-09-26 08:47:23

如果myString中有任何字母与myString中的所有字母匹配,则返回True。也可以反过来做,如果myString中有任何字母不匹配,则返回False

代码语言:javascript
复制
def findLetters(myList, myString):
    for letter in myString:
        if letter not in myList:
            return False
    return True

或者使用内置函数all

代码语言:javascript
复制
def findLetters(myList, myString):
  return all(letter in myList for letter in myString)
票数 0
EN

Stack Overflow用户

发布于 2017-09-26 08:50:00

您可以使用lambda映射所有字母,这将为my_string中的所有字母创建一个布尔值列表。

如果l列表中的所有值都为True,则函数all返回true

代码语言:javascript
复制
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'))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46416137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档