I have a python list of list as follows. I want to flatten it to a single list.
l = [u'[190215]']
I am trying.
l = [item for value in l for item in value]
It turns the list to [u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']
How to remove the u
from the list.
Method 1: Using map() + str.strip() In this, we employ strip(), which has the ability to remove the trailing and leading special unwanted characters from string list. The map(), is used to extend the logic to each element in list.
How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.
Use del to remove an element by index, pop() to remove it by index if you need the returned value, and remove() to delete an element by value.
The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings.
The u
means a unicode
string which should be perfectly fine to use.
But if you want to convert unicode
to str
(which just represents plain bytes in Python 2) then you may encode
it using a character encoding such as utf-8
.
>>> items = [u'[190215]']
>>> [item.encode('utf-8') for item in items]
['[190215]']
In your current code, you are iterating on a string, which represents a list, hence you get the individual characters.
>>> from ast import literal_eval
>>> l = [u'[190215]']
>>> l = [item for value in l for item in value]
>>> l
[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']
Seems to me, you want to convert the inner string representation of list, to a flattened list, so here you go:
>>> l = [u'[190215]']
>>> l = [item for value in l for item in literal_eval(value)]
>>> l
[190215]
The above will work only when all the inner lists are strings:
>>> l = [u'[190215]', u'[190216, 190217]']
>>> l = [item for value in l for item in literal_eval(value)]
>>> l
[190215, 190216, 190217]
>>> l = [u'[190215]', u'[190216, 190217]', [12, 12]]
>>> l = [item for value in l for item in literal_eval(value)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With