Search, delete and replace string from a tuple in the list, how to implement?

There is an array [('a', 'd', 'z', 'x'), ('b', 'e ', 'k', 'l'), ('b', 'e', 'm', 'n'), ('c', 'f', 'g', 'h'), ('c', 'f', 'y', 'w')]
The first two lines of the tuples can be the same and if so, then you need to combine these two into a single tuple
The condition of solutions:
The same line should remain in the same instance
The strings themselves can be in length not only 1 character and with spaces, for example: 'sdgs sdbvfsb'
Expected result:
[('a', 'd', 'z', 'x'), ('b', 'e ', 'k', 'l', 'm', 'n'), ('c', 'f', 'g', 'h', 'y', 'w')]
April 19th 20 at 12:21
2 answers
April 19th 20 at 12:23
from itertools import repeat
d = {}
for x in [('a', 'd', 'z', 'x'), ('b', 'e ', 'k', 'l'), ('b', 'e', 'm', 'n'), ('c', 'f', 'g', 'h'), ('c', 'f', 'y', 'w')]:
 d.setdefault(x[:2], {}).update(zip(x, repeat(None)))
print([list(v.keys()) for v in d.values()])

But you have a second tuple space near the "e" and, strictly speaking, your solution is wrong.
Either remove the space, or you can stripnude keys replacing x[:2] for tuple(map(str.strip, x[:2]))
There are not many used so as not to lose the order of the elements.
April 19th 20 at 12:25
>>> from collections import defaultdict
>>> d = defaultdict(tuple)
>>> for i in your_list:
 d[i[:2]] += i[2:]
>>> result = [i + d[i] for i in d]

Find more questions by tags Python