提取8位数字
问题描述:
我有可能包含字母,符号,数字等字符串列表,如下图所示:提取8位数字
list = ['\n', '', '0', '38059', '', '', '?_', '71229366', '', '1', '38059', '', '', '?_', '87640804', '', '2', '38059', '', '', '?_', '71758011', '', '', ':?', ';__', '71229366287640804271758011287169822']
如何过滤掉所有其他字符串,除了小于10000000且大于99999999的数字?
预期输出:
list = ['71229366', '87640804', '71758011']
答
如果你不介意做一个新的列表,你可以尝试的东西只是一个列表理解像
filtered_list = [i for i in list if i.isdigit() and 10000000 < int(i) < 99999999]
答
您可以使用map
和filter
。
your_list = ['\n', '', '0', '38059', '', '', '?_', '71229366', '', '1', '38059',
'', '', '?_', '87640804', '', '2', '38059', '', '', '?_', '71758011',
'', '', ':?', ';__', '71229366287640804271758011287169822']
new_list = list(map(int, filter(lambda x: x.isdigit() and 10000000 < int(x) < 99999999, your_list)))
print(new_list)
list()
python2上的可选项。
输出:
[71229366, 87640804, 71758011]
如果你不想整数转换,删除map
:
>>> list(filter(lambda x: x.isdigit() and 10000000 < int(x) < 99999999, your_list))
['71229366', '87640804', '71758011']
答
def valid(v):
try:
value = int(v)
return 10000000 <= value <= 99999999
except:
return False
output = [x for x in list if valid(x)]
说明:
使用有效函数作为标准过滤列表中的所有值。
答
data = ['\n', '', '0', '38059', '', '', '?_', '71229366', '', '1', '38059',
'', '', '?_', '87640804', '', '2', '38059', '', '', '?_', '71758011',
'', '', ':?', ';__', '71229366287640804271758011287169822']
res = []
for e in data:
try:
number = int(e)
except ValueError:
continue
if 10000000 < number < 99999999:
res.append(str(number))
打印(RES)
print(res)
输出:
['71229366', '87640804', '71758011']
答
让我提供一个简单而有效的回答,使用正则表达式。没有必要map
(复制原始列表),或将所有内容都转换为int
s;你基本上是问如何保持所有8位整数在您的列表:
>>> filter(re.compile('^\d{8}$').match, data)
['71229366', '87640804', '71758011']
我们compile
一个正则表达式,通过该标准提供的regex.match
部分应用程序匹配正好8个数字,然后过滤列表filter
功能。
什么意思与*所有字符*? – RomanPerekhrest
这里是没有字符的输出'''' –
尝试'list = None' – Jon