分隔转换后所有值都是数字的列表

Separating the lists where after conversion all values are numbers

为了只分离转换后的列表成为所有数字,我是这样做的:

a = ['start','nan','1.004569','0.8554','nan']
b = ['0.464','5','4.8784','2.411474','0.44']
c = ['start','start','start','start','nan']

full_list = [a,b,c]

for test in full_list:
    try:
        numbers = [float(i) if '.' in i or 'e' in i else int(i) for i in test]
        print(numbers)
        print(sum(numbers))
    except:
        pass

输出:

[0.464, 5, 4.8784, 2.411474, 0.44]
13.193874000000001

但在这些情况下使用 try except 似乎过时且不专业。我应该如何做到这一点,而不必查找错误来分隔正确的列表并在以后使用这些数字?

使用正则表达式方法验证数字格式。正则表达式不是最好的,但应该适用于正负整数或小数,并与科学记数法兼容。

import re

a = ['start','nan','1.004569','0.8554','nan']
b = ['0.464','-5','4.8784','2.411474','0.44', '-1.23e-07']
c = ['start','start','start','start','nan']

full_list = [a,b,c]

pattern = re.compile(r'^(-{,1}\d+\.{,1}\d*?)|(-{,1}\d+\.{,1}\d*?e[-\+]\d+)$')

full_results = []
for test in full_list:
    matches = [pattern.fullmatch(t) for t in test]
    if all(matches):
        results = [float(m.group()) for m in matches]
        full_results.append(results)