• Python | 二元嵌套列表分组


    有时候,在处理数据库时,我们需要执行某些列表操作,这些操作更像是查询语言,例如,将嵌套的列表元素相对于其他索引元素进行分组。本文讨论二元嵌套列表,并将每个嵌套列表元素相对于其其他索引元素进行分组。

    1. 列表解析

    # initializing list
    test_list = [["G", 0], ["F", 0], ["B", 2],
                 ["E", 2], ['I', 1], ['S', 1],
                 ['S', 2], ['T', 2], ['G', 0]]
     
    # using list comprehension
    # to perform binary list grouping
    temp = set(map(lambda i: i[1], test_list))
    res = [[j[0] for j in test_list if j[1] == i] for i in temp]
     
    # printing result
    print("The grouped list is : " + str(res))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    输出

    The grouped list is : [['G', 'F', 'G'], ['I', 'S'], ['B', 'E', 'S', 'T']]
    
    • 1

    2. 使用itertools.groupby + itemgetter

    我们也可以使用groupby函数来执行这个特定的任务。该方法遵循2-3个步骤。首先,序列相对于第二个元素进行排序,现在可以将其馈送以进行分组。最后,我们根据结果的要求打印第一个元素。

    from itertools import groupby
    from operator import itemgetter
     
    # Initializing list
    test_list = [["G", 0], ["F", 0], ["B", 2],
                 ["E", 2], ['I', 1], ['S', 1],
                 ['S', 2], ['T', 2], ['G', 0]]
     
    # Performing binary list grouping
    # using itertools.groupby() + itemgetter()
    test_list.sort(key=itemgetter(1))
    groups = groupby(test_list, itemgetter(1))
    res = [[i[0] for i in val] for (key, val) in groups]
     
    # Printing the resultant list
    print("The grouped list is : " + str(res))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    输出

    The grouped list is : [['G', 'F', 'G'], ['I', 'S'], ['B', 'E', 'S', 'T']]
    
    • 1

    3. 使用collections.defaultdict()

    import collections
    
    # initializing list
    test_list = [["G", 0], ["F", 0], ["B", 2],
    			["E", 2], ['I', 1], ['S', 1],
    			['S', 2], ['T', 2], ['G', 0]]
    
    # using collections.defaultdict()
    # to perform binary list grouping
    res = collections.defaultdict(list)
    for val in test_list:
    	res[val[1]].append(val[0])
    
    # printing result
    print("The grouped list is : " + str(res.values()))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    输出

    The grouped list is : dict_values([['G', 'F', 'G'], ['I', 'S'], ['B', 'E', 'S', 'T']])
    
    • 1

    4. 使用for循环 + sort

    1. 启动for循环以查找唯一的1索引元素
    2. 启动了一个嵌套的for循环,将所有具有相同1索引元素的字符分组
    3. 显示分组列表
    # initializing list
    test_list = [["G", 0], ["F", 0], ["B", 2],
                 ["E", 2], ['I', 1], ['S', 1],
                 ['S', 2], ['T', 2], ['G', 0]]
     
    # using list comprehension
    # to perform binary list grouping
    x = []
    for i in test_list:
        if i[1] not in x:
            x.append(i[1])
    x.sort()
    res = []
    for i in x:
        a = []
        for j in test_list:
            if j[1] == i:
                a.append(j[0])
        res.append(a)
    # printing result
    print("The grouped list is : " + str(res))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    输出

    The grouped list is : [['G', 'F', 'G'], ['I', 'S'], ['B', 'E', 'S', 'T']]
    
    • 1

    5. 使用numpy

    1. 导入别名np的numpy库。

    2. 创建输入列表test_list。

    3. 使用np.array函数将test_list转换为numpy数组,并将结果赋给变量arr

    4. 使用np.unique函数获取arr第二列的唯一值,并将结果赋给变量unique_values。

    5. 创建名为result_list的空列表。

    6. 对于unique_values中的每个唯一值i,执行以下操作:
      a.使用布尔索引来选择arr中第二列等于i的行
      b.从选定行的第一列提取值,并将其转换为列表。
      c.将结果列表附加到result_list。

    7. 打印生成的分组列表。

    import numpy as np
     
    # initializing list
    test_list = [["G", 0], ["F", 0], ["B", 2], ["E", 2],
                 ['I', 1], ['S', 1], ['S', 2], ['T', 2], ['G', 0]]
     
    arr = np.array(test_list)
     
    # Storing all unique values
    unique_values = np.unique(arr[:, 1])
     
    result_list = [list(arr[arr[:, 1] == i, 0]) for i in unique_values]
     
    # Printing the result
    print("The grouped list is:", result_list)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    输出

    The grouped list is: [['G', 'F', 'G'], ['I', 'S'], ['B', 'E', 'S', 'T']]
    
    • 1

    6. 使用dictionary和setdefault

    此方法使用字典按条目的第二个元素对条目进行分组,该元素充当字典中的键。setdefault方法用于创建一个空列表作为新键的值,或者将当前项的第一个元素附加到与该键关联的列表中。然后将生成的字典值转换为列表以获得最终结果。

    # initializing list
    test_list = [["G", 0], ["F", 0], ["B", 2],
                ["E", 2], ['I', 1], ['S', 1],
                ['S', 2], ['T', 2], ['G', 0]]
     
    # Using dictionary and setdefault() to perform binary list grouping
    group_dict = {}
    for item in test_list:
        group_dict.setdefault(item[1], []).append(item[0])
    res = list(group_dict.values())
     
    # printing result
    print ("The grouped list is : " + str(res))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    输出

    The grouped list is : [['G', 'F', 'G'], ['B', 'E', 'S', 'T'], ['I', 'S']]
    
    • 1

    7. 使用pandas

    它初始化一个名为test_list的列表,其中包含两个元素的子列表。然后,它将列表转换为pandas DataFrame,按每个子列表的第二个元素对DataFrame进行分组,应用lambda函数选择每个子列表的第一个元素,将结果pandas Series转换为列表,并打印分组后的列表。

    import pandas as pd
     
    # initializing list
    test_list = [["G", 0], ["F", 0], ["B", 2],
                ["E", 2], ['I', 1], ['S', 1],
                ['S', 2], ['T', 2], ['G', 0]]
     
    # converting list to DataFrame
    df = pd.DataFrame(test_list, columns=['value', 'group'])
     
    # grouping by group
    grouped = df.groupby('group')['value'].apply(lambda x: x.tolist()).tolist()
     
    # printing result
    print("The grouped list is: " + str(grouped))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    输出

    The grouped list is: [['G', 'F', 'G'], ['I', 'S'], ['B', 'E', 'S', 'T']]
    
    • 1

    8. 使用列表和索引

    # Initializing list
    test_list = [["G", 0], ["F", 0], ["B", 2],
                ["E", 2], ['I', 1], ['S', 1],
                ['S', 2], ['T', 2], ['G', 0]]
     
    num_groups = max([elem[1] for elem in test_list]) + 1
    grouped = [[] for _ in range(num_groups)]
     
    # Iterating over our input list
    for elem in test_list:
        grouped[elem[1]].append(elem[0])
     
    grouped = [lst for lst in grouped if lst]
     
    # Printing the result
    print("The grouped list is:", grouped)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    输出

    The grouped list is: [['G', 'F', 'G'], ['I', 'S'], ['B', 'E', 'S', 'T']]
    
    • 1
  • 相关阅读:
    NLog配置文件详解
    进程程序替换
    Linux基本指令(二)
    《对线面试官》| 高频 Linux 面试题 Part2
    利用Python进行数据分析系列之:数组和矢量计算
    Maven安装配置
    Nacos入门
    python---切片
    基础算法汇总
    github上star较多的三个c++ 内存池memory pool分析
  • 原文地址:https://blog.csdn.net/qq_42034590/article/details/132166779