简体   繁体   English

从元组列表中提取所有元素并将所有这些唯一元素放入列表中

[英]Extract all the elements from a list of tuples and put all those unique elements in a list

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

Output: Output:

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

Tried Code:试过的代码:

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

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 eg 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.否则需要更复杂的递归 function(第二种情况)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM