[英]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
:然后通过
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...如果您通过在已经表示列表的字符串上使用
split
方法获得list_1
的可能事件,我相信您可以弄清楚如何缩短这个过程......
Using Python 2:使用 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.在 Python 3
map
返回一个 map 对象,它只会懒惰地计算。 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]
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.