如何从嵌套的元组列表中获取每个元组的第一个元素?

How do I get the first element of every tuple from a nested list of tuples?

我正在尝试从嵌套的元组列表进行迭代以获取第一个元素。 我得到的只是零元组。 我要的是

###expected output
### [['d51', 'd874', 'd486','d329','d1328', 'd1268','d114','d792', 'd717','d522'],
###['d51, 'd874', 'd486','d329', 'd1328', 'd1268']]
tupple=[[('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d1328', 11), ('d1268', 11), ('d114', 11), ('d792', 10), ('d717', 10),('d522', 10)],
        [('d51', 23), ('d874', 20), ('d486', 15), ('d329', 12), ('d1328', 11), ('d1268', 11)]]
new=[]
slow=[i[0] for i in tupple]       
for item in tupple:
    new.append(item[0][:])
new

##output  [('d51', 23), ('d51', 23)]

您可以像这样使用列表理解:

new = [[item[0] for item in inner] for inner in tupple]

# [['d51', 'd874', 'd486', 'd329', 'd1328', 'd1268', 'd114', 'd792', 'd717', 'd522'], ['d51', 'd874', 'd486', 'd329', 'd1328', 'd1268']]

您可以使用内置 zip() 解包来获取每个内部列表的第一个元素。

data = ...
output = [next(zip(*items)) for items in data]

对于嵌套的元组 arbitrarily-deeply*:

from typing import Union, Tuple, List

NestedTuple = Union[List["NestedTuple"], Tuple[str, int]]
UnpackedNestedTuple = Union[List["UnpackedNestedTuple"], List[str]]


def extract_first_element(nested_tuples: List[NestedTuple]) -> UnpackedNestedTuple:
    return [el[0] if isinstance(el, tuple) else extract_first_element(el) for el in nested_tuples]



# #####################################
# TESTING
# #####################################

tupple = [ [ ("d51", 23), ("d874", 20), ("d486", 15), ("d329", 12), ("d1328", 11), ("d1268", 11), ("d114", 11), ("d792", 10), ("d717", 10), ("d522", 10), ], [ ("d51", 23), ("d874", 20), ("d486", 15), ("d329", 12), ("d1328", 11), ("d1268", 11), ], ]

assert extract_first_element(tupple) == [
    ["d51", "d874", "d486", "d329", "d1328", "d1268", "d114", "d792", "d717", "d522"],
    ["d51", "d874", "d486", "d329", "d1328", "d1268"],
]


# XXX: recursion depth can become an issue
recur_error_ex = tupple
for _ in range(100000):
    recur_error_ex = [recur_error_ex]

try:
    extract_first_element(recur_error_ex)  # RecursionError: maximum recursion depth exceeded
except RecursionError as e:
    print(f"WARNING: {e}")

* 达到最大递归深度。参见示例