📌  相关文章
📜  Python|根据值将元组分组到列表中

📅  最后修改于: 2022-05-13 01:54:49.129000             🧑  作者: Mango

Python|根据值将元组分组到列表中

有时,在使用Python元组时,我们可能会遇到一个问题,即我们需要根据分配给它的值将元组元素分组到嵌套列表中。这在许多分组应用程序中很有用。让我们讨论可以执行此任务的某些方式。

方法 #1:使用itemgetter() + 列表理解 + groupby()

上述功能的组合可用于执行此任务。在此,我们使用itemgetter()访问该值,并使用groupby()和列表推导执行分组逻辑。

# Python3 code to demonstrate working of
# Group tuple into list based on value
# using itemgetter() + list comprehension + groupby()
from operator import itemgetter
from itertools import groupby
  
# initialize list 
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Group tuple into list based on value
# using itemgetter() + list comprehension + groupby()
res = [[i for i, j in temp]\
      for key, temp in groupby(test_list, key = itemgetter(1))]
  
# printing result
print("The list after grouping by value : " + str(res))
输出 :
The original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]

方法 #2:使用map() + itemgetter() + groupby() + 列表理解

这个方法和上面的方法类似,唯一的区别是我们选择了map来形成keys作为嵌套列表来形成新的结果列表。

# Python3 code to demonstrate working of
# Group tuple into list based on value
# using map() + itemgetter() + groupby() + list comprehension
from operator import itemgetter
from itertools import groupby
  
# initialize list 
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Group tuple into list based on value
# using map() + itemgetter() + groupby() + list comprehension
res = [list(map(itemgetter(0), temp)) 
      for (key, temp) in groupby(test_list, itemgetter(1))]
  
# printing result
print("The list after grouping by value : " + str(res))
输出 :
The original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]