Python - 从枚举中命名参数

吉米特1988

问题:

采取以下措施:

def a(the_enumerate: enumerate):
   print("index: " + str(the_enumerate[0]), character: " + the_enumerate[1])

map(a, enumerate("test"))

有没有办法以比以下方式更好的方式命名索引和当前元素(字符):

index: int = the_enumerate[0]
character: int = the_enumerate[1]

也许它会是这样的:

def a(the_enumerate: enumerate(index: int, character: str)):
   print("index: " + str(the_enumerate[0]), character: " + the_enumerate[1])

map(a, enumerate("test"))

上下文

我的方法感觉可以用“更好”的方式编写,而我正在经历一个可以做的旅程:

# Version 1
def convert_pascal_casing_to_real_sentence(string_to_convert: str) -> str:
    def casing_check(the_enumerate: enumerate):
        result: str = ""

        if the_enumerate[0] != 0:
            result = " " +  the_enumerate[1].lower() if the_enumerate[1].isupper() else the_enumerate[1]
        else: 
            result = the_enumerate[1]
            
        return result

    return "".join(map(casing_check, enumerate(string_to_convert)))

# Version 2
def convert_pascal_casing_to_real_sentence(string_to_convert: str) -> str:
    output: str = ""

    for index, character in enumerate(string_to_convert):
        if index != 0:
            output += " " + character.lower() if character.isupper() else character
        else: 
            output += character

    return output

# Calling one of the two methods
print(convert_pascal_casing_to_real_sentence("HelloWorld"))
约翰·博尼法斯

您可以enumerate按如下方式解压缩值:

def a(the_enumerate: enumerate):
    index, char = the_enumerate
    print(f"index: {index} character: {char}")

给你:

index: 0 character: t
index: 1 character: e
index: 2 character: s
index: 3 character: t

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章