我有一个简单的列表如下:
lst = ['11 12221/n']
我想将第一项拆分成如下列表:
['11', '12221']
这对我来说似乎相对简单,但我无法让它工作。我的第一个方法是:
lst[0].split()
但是当我打印列表时没有发生任何变化。因此我尝试了:
newLst=[]
for x in lst:
newList.append(x.split())
但是从这里我得到
[['11', '12221\n']]
我想我一定是从根本上误解了列表理解,有人可以解释为什么我的代码不起作用以及应该如何完成吗?
谢谢
最佳答案
我相信你正在寻找这个:
>>> lst = ['11 12221\n']
>>> # Split on spaces explicitly so that the \n is preserved
>>> lst[0].split(" ")
['11', '12221\n']
>>> # Reassign lst to the list returned by lst[0].split(" ")
>>> lst = lst[0].split(" ")
>>> lst
['11', '12221\n']
>>>
关于python - 使用空格拆分 python 列表的第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23171482/