简体   繁体   English

从列表 python 中删除非数值

[英]Remove non numeric values from list python

How to do I go about removing non numerics from a list such as;如何从列表中删除非数字,例如;

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

to result in the following;导致以下情况;

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

I've found various samples of code but nothing is working for me.我找到了各种代码示例,但没有什么对我有用。

You could use a list comprehension with a regular expression to replace all non numeric characters:您可以使用带有正则表达式的列表理解来替换所有非数字字符:

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

Or alternatively, use str. isdigit或者,使用str. isdigit str. isdigit in a similar fashion along with str. join str. isdigit以与str. join类似的方式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

Some functions to look into:一些需要研究的函数:

  • string.split(delim) will tokenize a string by the given delimiter. string.split(delim) 将通过给定的分隔符标记一个字符串。
  • int(string) will parse a string into an integer int(string) 将字符串解析为整数
  • float(string) will parse a string into a floating point number. float(string) 将字符串解析为浮点数。

Edit: Oh, this is wrong - this would return the numeric value of each value in the list.编辑:哦,这是错误的 - 这将返回列表中每个值的数值。 Though, technically, you could just return string(output) for the string version虽然,从技术上讲,您可以只为字符串版本返回 string(output)

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

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