简体   繁体   中英

Remove 'u' from a python list

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.

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]']

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']

You can convert your unicode to normal string with str :

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

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

I think this issue occurred in python 2.7 but in latest python version u did not displayed when it run

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

output -: ['[', '1', '9', '0', '2', '1', '5', ']']

If you want to concatenate string items in a list into a single string, you can try this code

l = [u'[190215]']
l = [item for value in l for item in value]
l = ''.join(l)
print(l)

output -: [190215]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM