PDavis PDavis - 1 year ago 74
Python Question

Combining tuple elements from a list of tuples. Tuple elements are tuple and list

I'm relatively new with Python and am having a hard time coming up with a way to make the following work. Currently, I have a list of tuples (larger than

. The elements inside these tuples are 1) a tuple, and 2) a string (these strings are always one of two values: in the example
(can also be
, or any other two strings). The inner tuples include an
and a
of values (strings):

list_one = [(('id1', ['v1', 'v2']), 'A'), (('id2', ['v3', 'v4', 'v5', 'v6']), 'A'), (('id3', ['v11']), 'B'), (('id4', ['v12', 'v13']), 'B'), (('id5', ['v14', 'v16']), 'B'), (('id6', ['v17', 'v18', 'v21']), 'A')]

I'm trying, unsuccessfully, to create a new list that looks as follows:

new_list1 = [('id1',['v1', 'v2', 'v3', 'v4', 'v5', 'v6']), ('id3',['v11', 'v12', 'v13', 'v14', 'v16']), ('id6',['v17', 'v18', 'v21'])]

When the string value (A, B) changes it should create a new tuple with the first element being the id of the initial tuple where the A,B changes, and the second element being a list of the values ("v's") inside the initial lists. A list if dictionaries would also be fine, e.g:

new_list2 = [{'id1': ['v1','v2', 'v3', 'v4', 'v5', 'v6']}, {'id3':['v11', 'v12', 'v13', 'v14', 'v16']}, {'id6':['v17', 'v18', 'v21']}]

I appreciate any guidance.


s = list_one[0][1]
for tup in list_one:
if s in tup:


['v1', 'v2', 'v3', 'v4', 'v5', 'v6', ['v11'], ['v12', 'v13'], ['v14', 'v16'], 'v17', 'v18', 'v21']

which is not really what I'm looking for, as this creates a list around one the 'A' value, with lists of 'B' inside.

Answer Source

You can basically loop along, remembering what is the current key (initialized to None).

key = None # This is 'A' or 'B' in your example, but it starts off as None
new_list = [] # This holds the final result
for r, l in [(r, l) for (l, r) in list_one]: 
    if r != key: # If the current is not the key, time to switch to a new one
        id_ = l[0]
        new_list.append({id_: []})
    new_list[-1][id_].extend(l[1]) # Extend the current list
    key = r # Make it the current key in any case.

>>> new_list
[{'id1': ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']},
 {'id3': ['v11', 'v12', 'v13', 'v14', 'v16']},
 {'id6': ['v17', 'v18', 'v21']}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download