【问题标题】:Extend a list with another one. Why this behaviour?用另一个扩展一个列表。为什么会有这种行为?
【发布时间】:2019-05-23 03:11:26
【问题描述】:

我有一个 2 元素列表,我想用另一个元素的元素对其进行扩展。 在 Jupyter 中玩耍我发现了这种我无法理解的奇怪行为。

# this is my first list
columnslist=['app','SUM']
['app','SUM']

# it is going to be extended with the values A and B

columnslist.extend(['A','B'])
['app','SUM','A','B']

# It is possible to make a list out of a string in this way
print(list('AB'))
['A','B']

# I realise that list('AB')= ['A','B']
This works:
columnslist.extend(list('AB'))

# but the following does not work:
mytext='this is a text to be split'
columnslist.extend(mytext.split())

为什么会这样? 谢谢

【问题讨论】:

  • 你在哪里见过list[...],为什么你觉得这比你上面只使用一行的list(...)语法更正确?
  • 谢谢。那是一个错字
  • list['AB'] 不是正确的语法恕我直言。 list(['AB'])
  • 你用更不正确的东西修正了“错字”。
  • 错字已更正。我看到的是 list 将一个字符串放入 () 并给出一个列表,哪些元素是字符串的字符。 @cph:在 list(['AB']) 中,您传递给 list 一个列表,因为 ['AB'] 是一个包含一个元素的列表。 list(['AB']) 给出 ['AB'] 而不是 'A', 'B'。

标签: python list extend


【解决方案1】:

首先,将关键字用作变量是不好的做法。第二件事它不能使用扩展函数,因为它是一个字典对象。

编辑: 我希望我猜对了,您想在带有空格的字符串中提取字母吗?那么你可以试试下面的代码

>>>my_list= ["A","B"]
>>>test_str = "This is a text"
>>>my_list.extend(list("".join(test_str.split())))
['A','B','T', 'h', 'i', 's', 'i', 's', 'a', 't', 'e', 'x', 't']

【讨论】:

  • Gaurav,这只是一个例子。而且我是初学者。
  • 没关系。如果我的语气听起来很刺耳,我很抱歉。我只是简单地解释一下。继续前进
  • 无论如何,风吹过这个问题和低票。然而最后一个问题还没有解决。
  • 啊,当它的stackoverflow时总是发生这种情况,你想提取字符串的字母对吗?
【解决方案2】:

文字用空格隔开,这里可以使用.split.split 转换列表中的字符串。

columnslist.extend(mytext.split(' '))

【讨论】:

  • split 没有参数已经在空格上分割;这并没有真正添加任何东西。
猜你喜欢
  • 2023-03-22
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
相关资源
最近更新 更多