【问题标题】:Python List comprehension multiple if else conditionPython列表理解多个if else条件
【发布时间】:2020-08-27 18:05:45
【问题描述】:

list=["aeouis...,.,,esw","trees..,,ioee", '".....wwqqow..","...,...,,,","uouiyteerff..,,", ",w," ]

我需要创建第二个列表作为输出。每个元素的输出将是该元素中存在的唯一元音,或者 :用于字符串中 75% 或更多的元音, medium:元素中40-75%的元音, low:如果元素中元音少于 40% 或

没有元音:如果字符串中没有元音。

and Null:如果字符串长度小于5。

所以输出将是:[[a,e,o,u,i]low, [e,i,o]medium, No Vowels, No Vowels, [u,o,i,e]low, NULL]

我们可以使用列表理解来做到这一点吗??

【问题讨论】:

  • 你可以,但我建议先定义一个处理高/中/低/无/空业务的函数,因为这将是一个熊市。
  • 你能告诉我怎么做吗?

标签: python lambda list-comprehension string-matching dictionary-comprehension


【解决方案1】:

我会这样做:

from enum import Enum
from typing import List, Set, Tuple

VOWELS = set("aeiou")


class VowelScore(Enum):
    HIGH = "High"             # vowels >= 0.75
    MEDIUM = "medium"         # 0.75 > vowels >= .040
    LOW = "low"               # 0.40 > vowels
    NO_VOWELS = "No vowels"   # no vowels
    NULL = "Null"             # len < 5


def get_vowel_score(element: str) -> VowelScore:
    if len(element) < 5:
        return VowelScore.NULL
    vowels = [c for c in element if c in VOWELS]
    if len(vowels) == 0:
        return VowelScore.NO_VOWELS
    vowel_ratio = len(vowels) / len(element)
    if vowel_ratio < 0.40:
        return VowelScore.LOW
    if vowel_ratio < 0.75:
        return VowelScore.MEDIUM
    return VowelScore.HIGH


def get_vowel_list(elements: List[str]) -> List[Tuple[Set[str], VowelScore]]:
    return [
        (VOWELS & set(element), get_vowel_score(element))
        for element in elements
    ]

【讨论】:

    猜你喜欢
    • 2017-03-20
    • 2020-01-07
    • 2017-11-14
    • 2023-03-14
    • 2023-03-29
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多