Reputation: 17
Right now I have a nested list and I need a function to create a new list that combines element 0 and element 1 if they are the same. If they are the same it also adds the 3rd elements together.
Sample input:
input_list = [['123', '6', '2'], ['123','4','55'], ['123','6','3']
Expected output:
output_list = [['123','6','5'], ['123','4','55']]
123 and 6 were the same so it got combined and then 2+3=5
123,4,55 doesn't have any duplicates so it stays the same
Thank you in you advance
Upvotes: 0
Views: 59
Reputation: 319
Since you explained that you wanted guidance and not a complete answer, I will post my previous comment plus some extra discussion.
For me a solution would be to take out an element at a time, by using pop(), and then looking on the rest of the input by iterating and checking for any remaining elements with the same [0] and [1] items.
If there are, I would also pop() that element, sum the third element and completing the iteration. When it's complete, the resulting element goes to the output list.
Then repeat until there are no more elements on the input.
The idea behind this algorithm and I think on the other answer here, is trying to avoid processing more than once the same element. Probably any solution that doesn't use complete nested loops will be ok from a processing standpoint.
Upvotes: 0
Reputation: 106465
You can use a dict to aggregate values of the same key, and use a list comprehension to construct the desired output list from the dict:
output = {}
for *key, value in input_list:
key = tuple(key)
output[key] = output.get(key, 0) + int(value)
output_list = [[*key, str(value)] for key, value in output.items()]
output_list
becomes:
[['123', '6', '5'], ['123', '4', '55']]
Upvotes: 0
Reputation: 11228
for this problem since element at position 0 and 1 in inner list require to be same for the third value to be added together and then showing the result, so all one need to do was hash the first two values and if some repeat is coming then add the value for that hash pair.
in python dict provide this feature, so you can implement it that way
input_list = [['123', '6', '2'], ['123','4','55'], ['123','6','3']]
res = {}
for i in input_list:
if (i[0], i[1]) not in res:
res.update({(i[0], i[1]):int(i[2])})
else:
res[(i[0],i[1])]+=int(i[2])
output_list = [[k[0],k[1], str(v)] for k,v in res.items()]
print(output_list)
output
[['123', '6', '5'], ['123', '4', '55']]
Upvotes: 1