Append连接字符串,而不是将其添加到列表中

2024-09-28 22:34:10 发布

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

我想返回一个字符串列表,如下所示:

def get_regions():
    normalized_regions = []
    regions = [
        "auckland"
        "bay of plenty"
        "canterbury"
        "gisborne"
        "hawkes bay"
        "manawatu-whanganui"
        "marlborough"
        "northland"
        "otago"
        "southland"
        "taranaki"
        "tasman"
        "waikato"
        "wellington"
        "west coast"
    ]

    for r in regions:
        normalized_regions.append(normalize_location(r))
    return normalized_regions

normalize_location()是一个将字符串转换为小写并删除不必要空格的函数

我不明白为什么append()将元素连接为单个字符串,而不是将它们添加到列表中?请参见下面的屏幕截图:

enter image description here


Tags: of字符串列表getdeflocationnormalizeregions
1条回答
网友
1楼 · 发布于 2024-09-28 22:34:10

你会踢自己的。 这是因为列表中的每个条目后面都没有逗号。 你的名单应该是:

regions = [
    "auckland",
    "bay of plenty",
    "canterbury",
    "gisborne",
    "hawkes bay",
    "manawatu-whanganui",
    "marlborough",
    "northland",
    "otago",
    "southland",
    "taranaki",
    "tasman",
    "waikato",
    "wellington",
    "west coast",
]

相关问题 更多 >