首页 > 解决方案 > how to extract the first element of each tuple in each sublist?

问题描述

I have a list of lists and within each sublist there are tuples with the format (iD, volume). I need to keep the first element of each tuple and do away with the second while saving the new list of lists into binContents.

for example:

bins = [[(2, 22), (1, 13)], [(2, 22)], [(0, 20)]]
binContents = 

Desired outcome:

print(binContents)
[[2,1],[2],[0]]

*not a duplicate of How to make a flat list out of list of lists? because I do not intend on making a flat list, and that code with additional indexing did not give me my desired result

标签: python

解决方案


开始了:

bins = [[(2, 22), (1, 13)], [(2, 22)], [(0, 20)]]
binContents = [[y[0] for y in x] for x in bins]
print(binContents)

这产生

[[2, 1], [2], [0]]

推荐阅读