I'm iterating over a large list of tuples of the form
num_list = [('A15', 2, 'BC', 721.16), ('A21', 3, 'AB', 631.31), ('A42', 4, 'EE', 245.43)]
I'm trying to find the maximum fourth element of each tuple over a rolling 5 value period for the second element for each different value of the first element, all the different first element values are stored in a set called account_2 and output that in a form
ID Max
A21 400
A15 489
My code is below:
first_value = 1
fifth_value = 5
maximum = []
while first_value <= 24 and fifth_value <= 28:
for num_list[0][0] in account_2:
result = max([i for i in num_list if i[1] <= fifth_value and i[1] >= first_value], key = lambda x:x[3])
maximum.extend(result)
first_value += 1
fifth_value += 1
I think I need to substitute the 1st 0
in num_list[0][0]
for a variable to loop over so it loops over every single tuple in the list but in my testing of just the first tuple ie in the current case I'm getting the error TypeError: 'tuple' object does not support item assignment
.
Any help would be greatly appreciated. Thanks in advance
The error is caused by the line
for num_list[0][0] in account_2:
which tries to assign values from account_2
to numlist[0][0]
while numlist[0]
is a tuple, that is an immutable object.
The minimum fix would be:
while first_value <= 24 and fifth_value <= 28:
for acc in account_2:
try:
result = max([i for i in num_list if i[1] <= fifth_value and i[1] >= first_value and i[0] == acc ], key = lambda x:x[3])
except ValueError:
result = ()
maximum.extend(result)
first_value += 1
fifth_value += 1
The try: ... except...
is necessary because max
raises a ValueError when it is passed an empty sequence.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.