Home > Back-end >  Extract all the elements from a list of tuples and put all those unique elements in a list
Extract all the elements from a list of tuples and put all those unique elements in a list

Time:09-10

codes = [('A', ['B', 'C']), ('D', ['E', 'C'])]

Output:

['A', 'B','C','D','E']

Tried Code:

n = 1
e = [x[n] for x in codes]

CodePudding user response:

from itertools import chain
list(set(list(chain.from_iterable([val for sublist in list(map(list, zip(*codes))) for val in sublist]))))

CodePudding user response:

For the basic case shown there:

tuples = [("A", ["B", "C"]), ("A", ["B", "C"])]

unpacked = []

for current_tuple in tuples:
    # add the first element
    unpacked.append(current_tuple[0])
    # append all elements in the list to the tuple
    unpacked.extend(current_tuple[1])

for nesting of unknown depth

def get_all_elements(from_list) -> list:
    elements = []
    for item in from_list:
        if type(item) == list or type(item) == tuple:
            elements.extend(get_all_elements(item))
        else:
            elements.append(item)
            
    return elements

If all elements have a known and predictable structure e.g. 1st element is a string and 2nd element is a tuple of strings then the first case can be used. Otherwise the more complicated recursive function (second case) is required.

  • Related