cranberrysauce
cranberrysauce

Reputation: 51

Get all first element of tuples from list of lists of tuples in Python

Input: 
orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

Expected Output:  
orders = [['Fries'], ['Burger', 'Milkshare', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']]

My attempt:

 for i, order in enumerate(orders):
        for j,item in enumerate(order):
            orders[i][j] = item[0]

Works ok. But are there any more intuitive/one-liner/faster/cooler way to do this?

Upvotes: 0

Views: 1963

Answers (5)

Evan Wunder
Evan Wunder

Reputation: 131

You can isolate the keys by zipping up each order and returning the first index of each zip result.
The following gives you a list of tuples:

orders2 = [list(zip(*order))[0] for order in orders]

If you need a list of lists, use this:

orders2 = [list(a) for a in [list(zip(*order))[0] for order in orders]]

Code Example

orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

# For a list of tuples
orders2 = [list(zip(*order))[0] for order in orders]
print(*orders2) # ('Fries',) ('Burger', 'Milkshake', 'Cola') ('Cola', 'Nuggets', 'Onion Rings') ('Fries',) ('Big Burger', 'Nuggets')                         


# If you need a list of lists
orders2 = [list(a) for a in [list(zip(*order))[0] for order in orders]]
print(*orders2) # ['Fries'] ['Burger', 'Milkshake', 'Cola'] ['Cola', 'Nuggets', 'Onion Rings'] ['Fries'] ['Big Burger', 'Nuggets']                           


Live Code -> https://onlinegdb.com/SklIG1q6iU

Upvotes: 0

Balaji Ambresh
Balaji Ambresh

Reputation: 5012

Here you go:

output = [[item[0] for item in order] for order in orders]

Upvotes: 1

moctarjallo
moctarjallo

Reputation: 1615

output = [[item[0] for item in order] for order in orders]

display(output)

[['Fries'],
['Burger', 'Milkshake', 'Cola'],
['Cola', 'Nuggets', 'Onion Rings'],
['Fries'],
['Big Burger', 'Nuggets']]

Upvotes: 2

Code Pope
Code Pope

Reputation: 5449

Here with one loop and one one liner:

l=[]
for order in orders:
    l.append([name[0] for order in orders for name in order])
l

Output:

[['Fries'],
 ['Burger', 'Milkshake', 'Cola'],
 ['Cola', 'Nuggets', 'Onion Rings'],
 ['Fries'],
 ['Big Burger', 'Nuggets']]

Upvotes: -1

Peter Pesch
Peter Pesch

Reputation: 643

Or simply [[item[0] for item in order] for order in orders]

Upvotes: 2

Related Questions