简体   繁体   中英

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

Im trying to iterate from a nested list of tuples in order to grab the first element. What I am getting is just the tuple at zero. what I want is

###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)]

You can use a list comprehension like so:

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']]

You can use the builtin zip() with unpacking to get the first element of each inner list.

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

For tuples that are nested 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}")

* Up to maximum recursion depth. See example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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