Python - Как вывести строки, которые находятся в списке, с определенным количеством букв в них - PullRequest
0 голосов
/ 21 сентября 2018

Используя Python 3.7, у меня есть список, который содержит строки различной длины.Я пытаюсь использовать функции только для возврата строк, которые имеют две буквы - мой порог.В настоящее время я получаю одностроковый вывод «a», когда я действительно хочу, чтобы «a», «ab» и «ac» были напечатаны.Я не знаю, где я иду не так?Я знаю, что 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 ]

0 голосов
/ 21 сентября 2018

Включение ответа @ kevh в ваш код будет выглядеть так:

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())
0 голосов
/ 21 сентября 2018

Используйте понимание списка:

>>> 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...