简体   繁体   中英

Collecting first item of a list in a list of lists

I have a list that looks like the following one:

my_list = [[[(2,3,4,5)]],[[8,2,4,2]],[[9,0,0,0]]]

Now, I want to find a way to make a new list zero_list whose elements will be the 0th entries of each element in my_list . That is

zero_list = [2, 8, 9]

How could I make a for loop for iterating the 0th element of a list whose elements are lists themselves? Of course in my real example I have a much bigger such list with thousands of entries who are lists themselves.

PS I understand this is probably an easy question but I could not figure it out.

For any depth list you can use this recursive function

def get_first(seq):
    if isinstance(seq, (tuple, list)):
        return get_first(seq[0])
    return seq

def get_zero_list(seq):
    return [get_first(i) for i in seq]



my_list = [[[[[[[[(2,3,4,5)]]]]]]],[[8,2,4,2]],[[9,0,0,0]]]

print(get_zero_list(my_list)) # [2, 8, 9]

my_list = [[[[[[[[(2,3,4,5)]]]]]]],[[[[[[[('first', 3)]]]], 2, 3],2,4,2]],[[([['a', 2]]),0,0,0]]]

print(get_zero_list(my_list)) # [2, 'first', 'a']
Zero_list = [ items[0] for sublist in my_list for items in sublist] 

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