0

I'm sure this must be simple, but I'm a python noob, so I need some help. I have a list that looks the following way:

foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'], ['0', '0', 'dorsal'], ['0', '0', 'ventral'], ['0', '0', 'acroscopic']]

Notice that every word has 1 or 2 numbers to it. I want to substract number 2 from number 1 and then come with a dictionary that is: word, number. Foo would then look something like this:

foo = {'able','0.125'},{'unable', '-0.75'}...

it tried doing:

bar=[]
for a,b,c in foo:
   d=float(a)-float(b)
   bar.append((c,d))

But I got the error:

ValueError: could not convert string to float: 
4

5 回答 5

3

''无法转换为字符串。

bar = []
for a,b,c in foo:
    d = float(a or 0) - float(b or 0)
    bar.append((c,d))

但是,这不会成为字典。为此,您想要:

bar = {}
for a,b,c in foo:
    d = float(a or 0)-float(b or 0)
    bar[c] = d

或者使用字典理解的更短的方法:

bar = {sublist[2]: float(sublist[0] or 0) - float(sublist[1] or 0) for sublist in foo}
于 2013-07-31T16:26:51.133 回答
0

添加一个条件来验证字符串是否为空,例如''并将其转换为0

于 2013-07-31T16:26:32.103 回答
0

float('')不起作用。假设你想要0在这种情况下,我推荐一个辅助函数:

def safefloat(s):
    if not s: 
        return 0.0
    return float(s)

res = {}
for a, b, c in foo:
    res[c] = safefloat(a) - safefloat(b)

请注意,您可以用理解将字典放在一行中:

res = dict((c, safefloat(a) - safefloat(b)) for a, b, c in foo)

或 Python 2.7+ 中的 dict 理解:

res = {c: safefloat(a) - safefloat(b) for a, b, c in foo}
于 2013-07-31T16:27:02.697 回答
0

发生这种情况是因为在某些情况下它们是您可以编写的空字符串

d = float(a or '0') - float(b or '0')
于 2013-07-31T16:27:40.393 回答
0
>>> foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'],
           ['0', '0', 'dorsal'], ['0', '0', 'ventral'],
           ['0', '0', 'acroscopic']]
>>> dict((i[2], float(i[0] or 0) - float(i[1])) for i in foo)
{'acroscopic': 0.0, 'ventral': 0.0, 'unable': -0.75, 'able': 0.125,
 'dorsal': 0.0}
于 2013-07-31T16:31:37.183 回答