简体   繁体   English

从 Python 中的元组列表列表中获取元组的所有第一个元素

[英]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?但是有没有更直观/单线/更快/更酷的方式来做到这一点?

Or simply [[item[0] for item in order] for order in orders]或者只是[[item[0] for item in order] for order in orders]

Here you go:这里是 go:

output = [[item[0] for item in order] for order in orders]
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']]

You can isolate the keys by zipping up each order and returning the first index of each zip result.您可以通过压缩每个订单并返回每个 zip 结果的第一个索引来隔离密钥。
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实时代码-> https://onlinegdb.com/SklIG1q6iU

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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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