简体   繁体   English

列表理解替换非float或int的项

[英]List comprehension replacing items that are not float or int

I have a 2 item list. 我有一个2项目清单。

Sample inputs: 样本输入:

['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. 我需要寻找任何不是浮点数或int的东西并将其删除。 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: 我写了一些代码来找到'>'并拆分第一个项目,但我不知道如何让我的'新项目'取代旧项目:

Here is my current code: 这是我目前的代码:

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]

Or remove the float() to get the items as strings. 或者删除float()以将项目作为字符串。 You can use this list comprehension only if '>' or '<' are found in the string. 只有在字符串中找到“>”或“<”时,才能使用此列表推导。

Iterators work well here: 迭代器在这里工作得很好:

def numbers_only(l):
    for item in l:
        if '> ' in item:
            item = item.split()[1]
        try:
            yield float(item)
        except ValueError:
            pass
>>> values = ['> 10000', '5398.38770002321']
>>> list(numbers_only(values))
[10000.0, 5398.38770002321]

Normally, it's easier to create a new list than it is to iterate and modify the old list 通常,创建新列表比迭代和修改旧列表更容易

What about 关于什么

def stip_chars(lst):
    for item in lst:
        yield item.strip("> ")

new_values = [v for v in strip_chars(values) if is_number(v)]

?

If you want to edit the list in place rather than create a new list, you can iterate over it using enumerate : 如果要编辑列表而不是创建新列表,可以使用enumerate迭代它:

for (list_index, item) in enumerate(values):
    if '> ' in item:
        values[list_index] = ' '.join(item_part for item_part in item.split() if is_number(item_part))

Or however you want to construct your new value - I'm not sure what you want if you have '5 6' in your original list. 或者你想构建你的新价值 - 如果原始列表中有'5 6',我不确定你想要什么。

If you want a new list, you can do something similar with a list comprehension. 如果您想要一个新列表,您可以使用列表推导执行类似的操作。

values = ['> 10000', '5398.38770002321']
print [filter(lambda s: s in '0123456789.', v) for v in values]

RETURNS: 返回值:

['10000', '5398.38770002321']

List of strings, as requested. 根据要求提供字符串列表。

And to make it a function: 并使其成为一个功能:

def parse_number(value):
    return [filter(lambda s: s in '0123456789.', v) for v in values]

print parse_number(values)

As an added bonus, making this accept negative numbers would be as easy as adding a hyphen to the whitelisted string '0123456789.-' 作为额外的奖励,使这个接受负数就像在白名单字符串'0123456789.-'添加连字符一样简单'0123456789.-'

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

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