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条回答
家丑人穷心不美
2楼-- · 2020-06-09 08:35

This should be what you want:

[x for y in l for x in y.split(";")]

output:

['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
查看更多
对你真心纯属浪费
3楼-- · 2020-06-09 08:39

Split the strings and then use chain.from_iterable to combine them into a single list

>>> import itertools
>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [ x for x in itertools.chain.from_iterable( x.split(';') for x in l ) ]
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
查看更多
欢心
4楼-- · 2020-06-09 08:43

What you want to do is -

strtemp = ";".join(l)

The first line adds a ; to the end of MySpace so that while splitting, it does not give out MySpaceApple This will join l into one string and then you can just-

l1 = strtemp.split(";")

This works because strtemp is a string which has .split()

查看更多
Anthone
5楼-- · 2020-06-09 08:50

Hope this helps :)

>>> x = [i.split(";") for i in l]
>>> x
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> z = [j for i in x for j in i]
>>> z
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
>>> 
查看更多
Fickle 薄情
6楼-- · 2020-06-09 08:50

One possible solution I have tried right now is: (Make sure do it in general way using for, while with index)

>>> l=['Facebook;Google+;MySpace', 'Apple;Android']
>>> new1 = l[0].split(';')
>>> new1
['Facebook', 'Google+', 'MySpace']
>>> new2= l[1].split(';')`enter code here`
>>> new2
['Apple', 'Android']
>>> totalnew = new1 + new2
>>> totalnew
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
查看更多
Anthone
7楼-- · 2020-06-09 08:52

You can first concatenate the strings in the list with the separator ';' using the function join and then use the split function in order create the list:

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

l1 = ";".join(l)).split(";")  

print l1

outputs

['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

查看更多
登录 后发表回答