【问题标题】:Adding a list of strings to an existing key in a dict将字符串列表添加到字典中的现有键
【发布时间】:2022-01-21 17:02:14
【问题描述】:

我正在尝试将字符串添加到列表中(使用 .append() 在每个循环中添加新字符串),然后将列表添加到现有键中。问题是在将新字符串添加到列表之后,然后打印到控制台中的键 [...](如何摆脱这个 [...])示例:

x = {}
y = ["going home"]
x["key"].append(y)
y.append("after lunch")
x["key"].append(y)
print(x)
{'key' : ['going home', 'after lunch', [...]]}

感谢您的宝贵时间

【问题讨论】:

  • 可能缺少:x["key"] = [] 可重现。
  • 有什么问题/错误?见minimal reproducible example
  • 在相互添加列表时,还要注意区分 appendextend

标签: python list dictionary


【解决方案1】:

也许正确的行为是:

x = {}
y = ["going home"]
x["key"] = y
y.append("after lunch")
print(x)
{'key': ['going home', 'after lunch']}

【讨论】:

    【解决方案2】:

    另一种选择是使用list.extend

    x = {}
    x['key'] = []
    y = ["going home"]
    x["key"].extend(y)
    y = ["after lunch"]
    x["key"].extend(y)
    print(x)
    

    输出:

    {'key': ['going home', 'after lunch']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2012-11-10
      相关资源
      最近更新 更多