【问题标题】:Extract non-string elements in list python3 [duplicate]提取列表python3中的非字符串元素[重复]
【发布时间】:2019-01-12 19:46:22
【问题描述】:

我有一个列表,其中每个元素都存储为字符串

A = ['a', 'b', 'c', '100','200.6']

如何只提取数字元素

[100, 200.6]

我无法使用[float(i) for i in temp] 转换元素,因为字符串元素无法转换为浮点数。我需要保留字符串元素,只过滤掉数字元素。

【问题讨论】:

  • 你可以Filterdef is_number(s): try: float(s) return True except ValueError: return False filter(is_number, A) 这比添加你自己的for循环更干净

标签: python


【解决方案1】:

对于简单的情况,你可以使用re.match来检查元素是否匹配带小数点的数字,然后将其转换为浮点数

>>> A = ['a', 'b', 'c', '100', '200.6']
>>> import re
>>> [float(e) for e in A if re.match(r'\d+\.?\d*$', e)]
[100.0, 200.6]

但正如人们在 cmets 中指出的那样,如果您以非常规格式浮动,则必须编写一个实用函数来尽可能将字符串转换为浮点数,或者返回 None 然后 filter 列表

>>> def is_float(n):
...     try:
...         return float(n)
...     except:
...         return None
... 
>>>
>>> A = ['a', 'b', 'c', '100', '200.6']
>>> list(filter(is_float, A))
['100', '200.6']

【讨论】:

  • 例如'1e+10'呢?也是负数。
  • 这会遗漏大量可以转换为浮点数的字符串。到目前为止,最简单和最强大的选择是尝试演员,如副本所示。例如,在 Python 中,'10_000' 可以转换为浮点数。 This article 想到这里。
猜你喜欢
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 2016-05-25
  • 2018-06-09
  • 1970-01-01
  • 2018-08-30
  • 2011-07-04
相关资源
最近更新 更多