Home > Net >  python: remove single quotation mark from elements in list. AttributeError: 'list' object
python: remove single quotation mark from elements in list. AttributeError: 'list' object

Time:09-22

from this list

lst=['a,b,c','d,e']

I want to obtain the following one

lst=['a','b','c','d','e']

so I assumed that first of all the quotation marks from the first list should be removed, but this line

[i for i in lst.split(' ' ' ')]

produces this error message: AttributeError: 'list' object has no attribute 'split'

How should I change my code to get what I need ?

CodePudding user response:

I know I already answered, I just noticed that since the elements are strings and have comma separations, you could use str.join on the list then just str.split the result to get the desired output:

','.join(lst).split(',')

>>> lst = ['a,b,c','d,e']
>>> ','.join(lst).split(',')
['a', 'b', 'c', 'd', 'e']

Note this works in this case but only because of your particular values.

CodePudding user response:

If you want to use a list comprehension, it'll look like this:

[y for x in lst for y in x.split(',')]

The error is because you're calling split on a list, but you need to call it on a str. The for x in lst gives you strings as x, which you then call split(',') on to get y, which is what goes into the final list.

This is equivalent to:

output = []
for x in lst:
    for y in x.split(','):
        output.append(y)

CodePudding user response:

You should first iterate through each text in your lst list, split those texts on comma and then flatten the split text's characters into a list like this:

lst=['a,b,c','d,e']

character_lst = [char for text in lst for char in lst.split(",")
# character_list will contain ['a','b','c','d','e']

CodePudding user response:

Using itertools.chain:

from itertools import chain
list(chain(*(s.split(',') for s in lst)))

or as a (slower) full functional variant:

from itertools import chain
list(chain(*map(lambda x: x.split(','), lst)))

output:

['a', 'b', 'c', 'd', 'e']

CodePudding user response:

Without imports or nested loops:

lst = ['a,b,c','d,e']

output = []
for x in lst:
    output.extend(x.split(','))
  • Related