【问题标题】:Need explanation for strange behaviour with list [duplicate]需要用列表解释奇怪的行为[重复]
【发布时间】:2020-09-14 16:26:32
【问题描述】:

考虑下面的代码。

x='string1'
y='string2'
xlst=[x]
ylst=[y]
print(xlst)
print(ylst)
print("xlst={0} , ylst={1}, combined={2}".format(xlst,ylst,xlst.extend(ylst)))

输出是:

['string1']
['string2']
xlst=['string1', 'string2'] , ylst=['string2'], combined=None

我希望最后一行是

xlst=['string1'] , ylst=['string2'], combined=['string1', 'string2']

为什么xlst会包含y,为什么是扩展xlstNone的结果?

我想我应该从这里寻找答案,因为它对我来说确实像是一个错误。

【问题讨论】:

  • list.extend 不返回值。它就地“扩展”给定列表。
  • 另外,因为值是在放入字符串之前进行评估的,所以 xlist 在放入字符串之前已经扩展了
  • Format 是一个生成器。你能做一个变量来处理扩展对象吗?
  • 当然!谢谢你。我知道我错过了什么。

标签: python python-3.x


【解决方案1】:

如果您想打印两个列表的组合,您可以简单地使用+ 运算符:

xlst=['string1']
ylst=['string2']
print("xlst={0} , ylst={1}, combined={2}".format(xlst, ylst, xlst + ylst))

输出:

xlst=['string1'], ylst=['string2'], combined=['string1', 'string2']

【讨论】:

    猜你喜欢
    • 2017-04-30
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2013-06-17
    相关资源
    最近更新 更多