Z
Z
zxqb2020-04-16 17:07:49
Python
zxqb, 2020-04-16 17:07:49

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

2 answer(s)
S
Sergey Pankov, 2020-04-16
@zxqb

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 space near "e" in the second tuple and, strictly speaking, your solution is wrong.
Either remove the space, or you can strip the keys by replacing x[:2]with Sets are not used here, so as not to lose the order of the elements. tuple(map(str.strip, x[:2]))

A
aRegius, 2020-04-17
@aRegius

>>> 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]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question