本文介绍了列出理解替换不是float或int的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个项目清单.
样本输入:
['19(1,B7)', '20(1,B8)']
['16 Hyp', '16 Hyp']
['< 3.2', '38.3302615548213']
['18.6086945477694', '121.561539536844']
我需要查找浮点型或整数型的任何东西并将其删除.所以我需要上面的列表看起来像是:
I need to look for anything that isn's a float or an int and remove it. So what I need the above list to look like is:
['19(1,B7)', '20(1,B8)']
['16 Hyp', '16 Hyp']
['3.2', '38.3302615548213']
['18.6086945477694', '121.561539536844']
我写了一些代码来查找'>'并拆分了第一项,但是我不确定如何让我的'新项'代替旧项:
I wrote some code to find '> ' and split the first item but I am not sure how to have my 'new item' take the place of the old:
这是我当前的代码:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
for i in range(0,len(result_rows)):
out_row = []
for j in range(0,len(result_rows[i])-1):
values = result_rows[i][j].split('+')
for items in values:
if '> ' in items:
newItem=items.split()
for numberOnly in newItem:
if is_number(numberOnly):
values.append(numberOnly)
此(打印(值))的输出为
The output of this (print(values)) is
['< 3.2', '38.3302615548213', '3.2']
推荐答案
这看起来更像是一种真正的列表理解方法,可以完成您想要的事情...
This looks more like a true list comprehension way to do what you want...
def isfloat(string):
try:
float(string)
return True
except:
return False
[float(item) for s in mylist for item in s.split() if isfloat(item)]
#[10000.0, 5398.38770002321]
或删除float()
以将项目作为字符串获取.仅当'>'或'<'时,您才可以使用此列表推导在字符串中找到.
Or remove the float()
to get the items as strings. You can use this list comprehension only if '>' or '<' are found in the string.
这篇关于列出理解替换不是float或int的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!