【问题标题】:Append concatenates the strings instead of adding them to the list [duplicate]追加连接字符串而不是将它们添加到列表中[重复]
【发布时间】:2021-06-15 10:16:41
【问题描述】:

我要返回一个字符串列表,如下图:

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() 将元素连接为单个字符串而不是将它们添加到列表中?请看下面的截图:

【问题讨论】:

  • 列表中的元素之间没有逗号
  • Python 自动字符串连接再次出现(更多信息请参阅this question
  • @user1558604,非常感谢!我的坏:-)
  • 这不应该被认为是重复的,因为 OP 没有尝试来做这种字符串连接。而是一种错字形式。

标签: python python-3.x


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多