[英]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:
['A', 'B','C','D','E']
試過的代碼:
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]))))
對於那里顯示的基本情況:
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])
用於未知深度的嵌套
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
如果所有元素都具有已知且可預測的結構,例如第一個元素是字符串,第二個元素是字符串元組,則可以使用第一種情況。 否則需要更復雜的遞歸 function(第二種情況)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.