Python 2: AttributeError: 'list' object ha

2020-06-09 07:56发布

I have a small problem with list. So i have a list called l:

l = ['Facebook;Google+;MySpace', 'Apple;Android']

And as you can see I have only 2 strings in my list. I want to separate my list l by ';' and put my new 5 strings into a new list called l1.

How can I do that?

And also I have tried to do this like this:

l1 = l.strip().split(';')

But Python give me an error:

AttributeError: 'list' object has no attribute 'strip'

So if 'list' object has no attribute 'strip' or 'split', how can I split a list?

Thanks

8条回答
可以哭但决不认输i
2楼-- · 2020-06-09 08:53

strip() is a method for strings, you are calling it on a list, hence the error.

>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False

To do what you want, just do

>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]

Since, you want the elements to be in a single list (and not a list of lists), you have two options.

  1. Create an empty list and append elements to it.
  2. Flatten the list.

To do the first, follow the code:

>>> l1 = []
>>> for elem in l:
        l1.extend(elem.strip().split(';'))  
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

To do the second, use 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']
查看更多
相关推荐>>
3楼-- · 2020-06-09 08:53

You split the string entry of the list. l[0].strip()

查看更多
登录 后发表回答