Answer the question
In order to leave comments, you need to log in
Finding, deleting and replacing a string from a tuple in a 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 rows of tuples can be the same and if so, then you need to combine these two tuples into one common
Solution condition:
Identical strings must remain in one instance
Strings themselves can be not only 1 character long 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')]
Answer the question
In order to leave comments, you need to log in
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()])
x[:2]
with Sets are
not used here, so as not to lose the order of the elements. tuple(map(str.strip, x[:2]))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question