从Python列表中删除非数字值

4

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

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

使结果如下:
['1500', '2200', '1200']

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


这回答解决了你的问题吗?如何在Python中将货币字符串转换为浮点数? 如果你从不涉及到分,你可以用简单的int替换Decimal... - Tomerikoo
2
我找到了各种代码示例,但没有一个适用于我。好的,选择你尝试过的最舒适的一个,并发布你的尝试以及你的结果与你所希望的有何不同。 - user5386938
如果字符串具有固定格式,为什么不使用正则表达式呢?在您的情况下,您可以使用以下 re 找到价格:'\$([0-9,]*).*'。也许您会得到 1,500 作为组结果。获取此结果后,您可以轻松地使用 locale.atoi 解析数字。 - user12688644
2个回答

7
你可以使用列表推导式和正则表达式来替换所有非数字字符:
你可以使用带有正则表达式的列表推导式来替换所有非数字字符:
>>> 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.isdigitstr.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']

没问题,很乐意帮忙。 - Sash Sinha

1
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) 作为字符串版本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接