我有一个嵌套元组列表,其中第二个元素是na float:
l = [('drink', ['vodka', '9.2', 'beer', '6.3', 'alcohol', '5.4', 'gin', '2.1', 'liquid']),
('evict', ['tenant', '66.0', 'squatter', '2.75', 'owner', '1.1', 'bum', '1.0', 'deadbeat', '1.0'])]
我想总结列表中的三个第一项,并将结果追加到开头,如下所示:
l = [('drink', 20.9 ['vodka', '9.2', 'beer', '6.3', 'alcohol', '5.4', 'gin', '2.1']),
('evict', 69.75 ['tenant', '66.0', 'squatter', '2.75', 'bum', '1.0', 'deadbeat', '1.0'])]
我正在使用以下代码:
sorted_by_sum=[]
for t in l:
tup=[t[0]]
tup.append(t[1])
tup.append(sum(float(x) for x in t[0][1:6:2]))
sorted_by_sum.append(tuple(tup))
但我得到了错误:
ValueError: could not convert string to float: 'a'
有关如何纠正此问题的任何提示?我非常感谢你。
答案 0 :(得分:3)
您想要访问元组的第二个元素来求和;不是t[0]
(字符串):
tup.append(sum(float(x) for x in t[1][1:6:2]))
但请将其作为第一个.append()
语句,而不是第二个。
您可以将整个循环转换为列表解析,使用元组解包为每个元组的两个元素提供更容易的名称:
sorted_by_sum = [(name, sum(float(x) for x in items[1:6:2]), items)
for name, items in l]
演示:
>>> l = [('drink', ['vodka', '9.2', 'beer', '6.3', 'alcohol', '5.4', 'gin', '2.1', 'liquid']),
... ('evict', ['tenant', '66.0', 'squatter', '2.75', 'owner', '1.1', 'bum', '1.0', 'deadbeat', '1.0'])]
>>> [(name, sum(float(x) for x in items[1:6:2]), items) for name, items in l]
[('drink', 20.9, ['vodka', '9.2', 'beer', '6.3', 'alcohol', '5.4', 'gin', '2.1', 'liquid']), ('evict', 69.85, ['tenant', '66.0', 'squatter', '2.75', 'owner', '1.1', 'bum', '1.0', 'deadbeat', '1.0'])]