【问题标题】:New list containing list + string包含列表 + 字符串的新列表
【发布时间】:2019-07-19 19:38:42
【问题描述】:

如何创建一个包含现有列表 + 新字符串的新列表?

Const1 = "1000"
Const2 = "2000"
Const3 = "3000"
CONST_LIST = [Const1, Const2]
CONST_LIST_NEW = [CONST_LIST] + Const3 #Nogo
print CONST_LIST_NEW

希望输出..... ['1000', '2000', '3000']

【问题讨论】:

标签: python string python-2.7 list


【解决方案1】:

如果你查看解释器给你的错误,你会看到有一个 TypeError:TypeError: can only concatenate list (not "str") to list

所以你需要连接两个列表,并且由于 CONT_LIST 已经是一个列表,所以不需要在它周围加上方括号。但是你的字符串需要在一个新列表中,所以只需输入[Const3]

最后看起来像这样:

Const1 = "1000"
Const2 = "2000"
Const3 = "3000"
CONST_LIST = [Const1, Const2]
CONST_LIST_NEW = CONST_LIST + [Const3]
print CONST_LIST_NEW

【讨论】:

  • 谢谢。但这不是要出局吗? (['1000', '2000'], ['3000'])
  • 对于其他想知道的人,(['1000', '2000'], ['3000']) 的输出是在您离开 [CONT_LIST] 时给出的。在上述问题的@Chris 评论中可以看到一个很好的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 2022-10-23
相关资源
最近更新 更多