Remove 'u' from the python list.

I have a list of python lists as follows. I want to smooth it into one list.

l = [u'[190215]'] 

I'm trying to.

 l = [item for value in l for item in value] 

It turns the list into [u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']

How to remove u from the list.

+6
source share
4 answers

In your current code, you iterate over a string that represents a list, so you get 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']'] 

It seems to me that you want to convert the internal string representation of the list into a flattened list, so here you are:

 >>> l = [u'[190215]'] >>> l = [item for value in l for item in literal_eval(value)] >>> l [190215] 

The above will only work when all internal 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 
+2
source

u means a unicode string, which should be perfect for use. But if you want to convert unicode to str (which just represents simple bytes in Python 2), you can encode use it with character encoding like utf-8 .

 >>> items = [u'[190215]'] >>> [item.encode('utf-8') for item in items] ['[190215]'] 
+8
source

You can convert your unicode to a regular string with str :

 >>> list(str(l[0])) ['[', '1', '9', '0', '2', '1', '5', ']'] 
+3
source

use [str(item) for item in list]

Example

 >>> li = [u'a', u'b', u'c', u'd'] >>> print li [u'a', u'b', u'c', u'd'] >>> li_u_removed = [str(i) for i in li] >>> print li_u_removed ['a', 'b', 'c', 'd'] 
+2
source

Source: https://habr.com/ru/post/989509/


All Articles