How to join tuples if the initial element are similar in Python

2 Answers

0 votes
from collections import defaultdict

list_tpl = [(4, 9), (4, 0), (5, 6), (5, 83), (4, 3), (6, 11)]
 
_map = defaultdict(list)
for key, val in list_tpl:
    _map[key].append(val)

result = [(key, *val) for key, val in _map.items()]
 
print(result)




'''
run:

[(4, 9, 0, 3), (5, 6, 83), (6, 11)]

'''

 



answered Dec 16, 2023 by avibootz
0 votes
list_tpl = [(4, 9), (4, 0), (5, 6), (5, 83), (4, 3), (6, 11)]
 
dict = {}
for t in list_tpl:
    dict[t[0]] = dict.get(t[0], []) + list(t[1:])
 
result = [(key,) + tuple(val) for key, val in dict.items()]
 
print(result)





'''
run:

[(4, 9, 0, 3), (5, 6, 83), (6, 11)]

'''

 



answered Dec 16, 2023 by avibootz

Related questions

2 answers 322 views
1 answer 176 views
176 views asked Dec 18, 2018 by avibootz
1 answer 181 views
181 views asked Dec 18, 2018 by avibootz
2 answers 205 views
1 answer 241 views
...