📜  Python – 从字符串列表中过滤浮点字符串

📅  最后修改于: 2022-05-13 01:55:30.164000             🧑  作者: Mango

Python – 从字符串列表中过滤浮点字符串

有时,在使用Python列表时,我们可能会遇到需要将浮点值与有效字符串分开的问题。但是当浮点值采用字符串形式时,就会出现问题。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环+异常处理
上述功能的组合可用于执行此任务。在此,我们遍历每个元素并尝试将每个字符串转换为浮点值,如果成功,则表示它是浮点数,否则会引发 ValueError 并且我们可以获得所需的字符串。

# Python3 code to demonstrate working of
# Filter float strings from String list
# using loop + Exception Handling
  
# initialize list 
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
  
# printing original list 
print("The original list : " + str(test_list))
  
# Filter float strings from String list
# using loop + Exception Handling
res = []
for ele in test_list:
    try:
        float(ele)
    except ValueError:
        res.append(ele)
  
# printing result
print("String list after filtering floats : " + str(res))
输出 :
The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

方法 #2:使用正则表达式 + 列表理解
上述功能的组合可以执行此任务。在此,我们使用创建的正则表达式执行过滤任务,列表理解用于迭代列表并应用过滤器。

# Python3 code to demonstrate working of
# Filter float strings from String list
# using regex + list comprehension
import re
  
# initialize list 
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
  
# printing original list 
print("The original list : " + str(test_list))
  
# Filter float strings from String list
# using regex + list comprehension
temp = re.compile(r'\d+(?:\.\d*)')
res = [ele for ele in test_list if not temp.match(ele)]
  
# printing result
print("String list after filtering floats : " + str(res))
输出 :
The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']