Python列表理解多if-else条件

2024-10-03 04:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我需要创建第二个列表作为输出。每个元素的输出将包含该元素中存在的唯一元音,并且 :对于strin中75%或以上的元音, 中等:元素中40-75%的元音, :如果元素中的元音少于40%,或

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

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

因此,输出将类似:[[a,e,o,u,i]low[e,i,o]medium,没有元音,没有元音,[u,o,i,e]low, NULL]

我们可以用列表来理解吗


Tags: 字符串元素列表nulltreeslowmedium元音
1条回答
网友
1楼 · 发布于 2024-10-03 04:25:28

我会这样做:

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
    ]

相关问题 更多 >