代码之家  ›  专栏  ›  技术社区  ›  Pendle S

Python—如何输出列表中包含一定数量字母的字符串

  •  1
  • Pendle S  · 技术社区  · 8 年前

    使用Python3.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的新手。。。

    2 回复  |  直到 8 年前
        1
  •  1
  •   kevh    8 年前

    >>> 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)
    
        2
  •  1
  •   lyxal    8 年前

    threshold = 2
    
    def listOfWords(list):
        stringList = ["a", "ab", "abc", "ac", "abcd"]
        return stringList
    
    def wordsInListsCounter():
        elements = listOfWords(list)
    
        if len(elements) != 0:
             strLessThanThreshold = [x for x in elements if len(x) <= threshold]
             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())
    

    但是,如果不想使用列表理解,可以使用以下方法:

    threshold = 2
    def listOfWords(list):
        stringList = ["a", "ab", "abc", "ac", "abcd"]
        return stringList
    
    def wordsInListsCounter():
        strLessThanThreshold = []
        elements = listOfWords(list)
    
        for element in elements :
            if len(element) <= threshold:
                strLessThanThreshold.append(element)
    
        if len(elements) == 0:
            emptyString = "There are no words in this list"
            return emptyString
    
        return strLessThanThreshold
    
    print(wordsInListsCounter())
    
    推荐文章