首页 > 解决方案 > Python - 如何输出列表中包含一定数量字母的字符串

问题描述

使用 Python 3.7,我有一个包含各种长度的字符串的列表。我正在尝试使用函数只返回有两个字母的字符串——我的阈值。当我真的想要打印“a”、“ab”和“ac”时,我目前得到了“a”的单个字符串输出。我不知道我哪里出错了?我知道 len(xStr) 会计算字符串中的字母数,但我不确定如何在这里正确使用它。

这是我尝试的代码:

threshold = 2
def listOfWords(list):
    stringList = ["a", "ab", "abc", "ac", "abcd"]
    return stringList

def wordsInListsCounter():
    for elements in listOfWords(list):
        if len(elements) <= threshold:
            strLessThanThreshold = elements
            return strLessThanThreshold
        elif len(elements) == 0:
            emptyString = "There are no words in this list"
            return emptyString
        else:
            error = "There is invalid information"
            return error
print(wordsInListsCounter())

任何帮助,将不胜感激!!我是这里的新手 Python 用户...

标签: python-3.xlistfunction

解决方案


使用列表推导:

>>> stringList = ["a", "ab", "abc", "ac", "abcd"]
>>> modifiedList = [x for x in stringList if len(x) <= 2]
>>> modifiedList
['a', 'ab', 'ac']

我已经编辑了我的答案以更好地匹配您的问题,这是我要添加的内容:

threshold = 2
myList = ["a", "ab", "abc", "ac", "abcd"]

def wordsInListsCounter(stringList):
    elements = []
    for element in stringList:
        if len(element) <= threshold:
            elements.append(element)
    return elements

elements = wordsInListsCounter(myList)

if len(elements) == 0:
    print("There are no words in this list")

else:
    print(elements)

推荐阅读