I have list where it has values of multiple persons, I want to calculate every alternate values in list of lists, how can I achieve it? list looks like below
for j in persons:
person_list.append(persons[int(j)][0] persons[int(j)][2])
person_list.append(persons[int(j)][1] persons[int(j)][3])
print("person list", person_list)
Above is the code which I tried, but it's not working
person [[222, 1, 255, 54], [105, 1, 135, 48], [397, 310, 521, 594]]
I have to calculate 222 255 and 1 54 and similarly for other lists.
CodePudding user response:
You can do something like this:
>>> x = [[222, 1, 255, 54], [105, 1, 135, 48], [397, 310, 521, 594]]
>>> [[sum(i[::2]), sum(i[1::2])] for i in x]
[[477, 55], [240, 49], [918, 904]]
This will go over and sum the even-indexed values together and the same with the odd-indexed values.