简体   繁体   中英

How to remove unused characters from a list of strings

For example, my list is:

list_1 =  [ '[1234,', '4567,', '19234,', '786222]' ]

and the expected output is:

list_1 = [1234, 4567, 19234, 786222]

Frankly, the easiest way to get a list of integers back out of that is to put it back together as a string representing a list:

>>> list_1 = ['[1234,', '4567,', '19234,', '786222]']

>>> list_repr = ' '.join(list_1)
>>> list_repr
'[1234, 4567, 19234, 786222]'

And then feed it through ast.literal_eval :

>>> from ast import literal_eval
>>> literal_eval(list_repr)
[1234, 4567, 19234, 786222]

In the likely event that you got list_1 by using the split method on a string that already represented a list in the first place, I'm sure you can figure out how to shorten this process...

You canstrip the bad characters and convert to int .

>>> [int(s.strip("[],")) for s in list_1]
[1234, 4567, 19234, 786222]

Using Python 2:

>>> map(int, ''.join(list_1).strip('[]').split(','))
[1234, 4567, 19234, 786222]

In Python 3 map returns a map object which only lazily evaluates. To create the list we need to be explicit. This is a good thing, more efficient and general:

>>> list(map(int, ''.join(list_1).strip('[]').split(',')))
[1234, 4567, 19234, 786222]

You can use translate to remove your unwanted characters.

>>> [int(s.translate(None,"[],")) for s in list_1]
[1234, 4567, 19234, 786222]

Hope this helps.

If you don't know the set of "bad" characters up front, you can also filter all digits from each string and then convert the result to an integer:

>>> list_1 =  [ '[1234,', '4567,', '19234,', '786222]' ]
>>> [int(filter(lambda x: x.isdigit(), s)) for s in list_1]
[1234, 4567, 19234, 786222]

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