繁体   English   中英

从列表 python 中删除非数值

[英]Remove non numeric values from list python

如何从列表中删除非数字,例如;

['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']

导致以下情况;

['1500', '2200', '1200']

我找到了各种代码示例,但没有什么对我有用。

您可以使用带有正则表达式的列表理解来替换所有非数字字符:

>>> import re
>>> lst = ['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
>>> lst
['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
>>> new_lst = [re.sub("[^0-9]", "", s) for s in lst]
>>> new_lst
['1500', '2200', '1200']

或者,使用str. isdigit str. isdigit以与str. join类似的方式str. join str. join

>>> lst = ['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
>>> lst
['$1,500 / month ', '$2,200 / month ', '$1,200 / month ']
>>> new_lst = [''.join(ch for ch in s if ch.isdigit()) for s in lst]
>>> new_lst
['1500', '2200', '1200']
Tokenize so that you only have the number string.
Tokenize by the comma, call the result tokens.
Set output = 0
For each token in tokens:
    multiply output by 1000
    parse token, call the result newnum
    add newnum to output
return output

一些需要研究的函数:

  • string.split(delim) 将通过给定的分隔符标记一个字符串。
  • int(string) 将字符串解析为整数
  • float(string) 将字符串解析为浮点数。

编辑:哦,这是错误的 - 这将返回列表中每个值的数值。 虽然,从技术上讲,您可以只为字符串版本返回 string(output)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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