Home > Software engineering >  How do you extract tuple elements and do some operations on them?
How do you extract tuple elements and do some operations on them?

Time:01-01

Input:

lits_tuple = [
("x1", "x2", "x3", "x4",    2),
("x1", "x4",    80),
("x4", "z1",    24)]

the last element will always be a numeric, float or integer

Expected Result:

{"x1": 82} # Because we had x1 in the first tuple with value 2, and x1 in tuple2 with value 80; 2 80 = 82

{"x2": 2} # Because we had x2 only in the first tuple with value 2

{"x3": 2} # Because we had x3 only in the first tuple with value 2

{"x4": 106} # Because we had x4 in the first tuple with value 2, and x4 in tuple2 with value 80 and x4 in tuple3 with value 24; 2 80 24 = 106

{"z1": 24} # Because we had z1 only in the last tuple with value 24

I started extracting the tuple manually to see if I can generalize, but then got tired and fell asleep.


tuple1 = lits_tuple[0]
last_element_tuple1 = tuple1[-1]
range_other_element_tuple1 = [i for i in range(len(lits_tuple[0])-1) ]
len_other_element_tuple1 = len(lits_tuple[0])-1




last_element_tuplek = lits_tuple[k-1][-1]
range_other_element_tuplek = [i for i in range(len(lits_tuple[k-1])-1) ]
len_other_element_tuplek = len(lits_tuple[k-1])-1

CodePudding user response:

You may iterate on each keys,nb rows, with the pack syntax *keys so all first elements are collected in keys and the last one in nb

Then use a defaultdict to increment each one's value

from collections import defaultdict

values = [
    ("x1", "x2", "x3", "x4", 2),
    ("x1", "x4", 80),
    ("x4", "z1", 24)
]

results = defaultdict(int)

for *keys, nb in values:
    for key in keys:
        results[key]  = nb

print(results)
# {'x1': 82, 'x2': 2, 'x3': 2, 'x4': 106, 'z1': 24}
  • Related