我有一个关于列表的小问题。所以我有一个名为 l
的列表:
l = ['Facebook;Google+;MySpace', 'Apple;Android']
如您所见,我的列表中只有 2 个字符串。我想用 ';' 分隔列表 l
并将新的 5 个字符串放入名为 l1
的新列表中。
我该怎么做?
我也试过这样做:
l1 = l.strip().split(';')
但是 Python 给我一个错误:
AttributeError: 'list' object has no attribute 'strip'
如果“list”对象没有属性“strip”或“split”,我该如何拆分列表?
谢谢
最佳答案
strip()
是字符串的一种方法,您在 list
上调用它,因此会出现错误。
>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False
做自己想做的事
>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
因为您希望元素位于单个列表(而不是列表的列表)中,所以您有两个选择。
- 创建一个空列表并向其添加元素。
- 展开列表。
首先,请遵循以下代码:
>>> l1 = []
>>> for elem in l:
l1.extend(elem.strip().split(';'))
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
要执行第二个操作,请使用 itertools.chain
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> from itertools import chain
>>> list(chain(*l1))
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
关于 python 2 : AttributeError: 'list' object has no attribute 'strip' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17751322/