如何解决此ValueError:无法将字符串转换为float?

时间:2019-03-14 19:48:47

标签: python python-2.7

我想对所有列表对象进行数学运算:

swl = ['0', '0', '0', '', '', '', '1', '1', '1', '1', '1', '0.25']

数学运算:sgu = 1 - swl,我想将sgu格式化为:

sgu_compact = ['3*1', '3*', '5*0', '0.75']

这就是我所拥有的:

sgu = []
for ii in range(0, int(len(swl))):
    if len(swl[ii]) == 0:
        sgu.append(swl[ii])
    else:
        sgu.append(1-float(swl[ii]))

sguflt = [float(x) for x in swl]
sgu2 = ['{:g}'.format(float('{:.6g}'.format(i))) for i in sgu]

sgu_compact = ['%s*' % len(l) * (len(l) > 1) + k for k, g in groupby(sgu2)
                for l in (list(g),)]

print sgu_compact

但是由于空列表对象,我得到ValueError。有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

只需过滤掉空值:

swl = ['0', '0', '0', '', '', '', '1', '1', '1', '1', '1', '0.25']
swl = [x for x in swl if len(x)]

答案 1 :(得分:0)

这可能可以进行更多优化,但是按照目前的样子,它可以满足您的要求。基本上,它只是检查并传递每个步骤中遇到的任何空字符串值。

from itertools import groupby

swl = ['0', '0', '0', '', '', '', '1', '1', '1', '1', '1', '0.25']

sgu = []
for value in swl:
    if len(value):
        sgu.append(1 - float(value))
    else:
        sgu.append(value)

sguflt = [float(x) if x is not '' else '' for x in swl]

sgu2 = ['{:g}'.format(float('{:.6g}'.format(i))) if i is not '' else '' for i in sgu]

sgu_compact = ['%s*' % len(l) * (len(l) > 1) + k for k, g in groupby(sgu2)
                for l in (list(g),)]

print sgu_compact  # -> ['3*1', '3*', '5*0', '0.75']