Reputation: 105
I have a list of nested tuples in which the second element is 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'])]
I want to sum the three first items on the list, and append the result to the beginning, like this:
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'])]
I am using the code below:
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))
But I am getting the mistake:
ValueError: could not convert string to float: 'a'
Any hints on what how to correct this? I thank you very much in advance.
Upvotes: 0
Views: 940
Reputation: 1124798
You want to access the second element of the tuple to sum; not t[0]
(the string):
tup.append(sum(float(x) for x in t[1][1:6:2]))
but make that the first .append()
statement, not the second.
You can turn the whole loop into a list comprehension, using tuple unpacking to give easier to follow names to the two elements of each tuple:
sorted_by_sum = [(name, sum(float(x) for x in items[1:6:2]), items)
for name, items in l]
Demo:
>>> 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'])]
Upvotes: 3