浅析python中的二元嵌套列表分组

 更新时间:2023年09月15日 09:49:14   作者:python收藏家  
这篇文章主要来和大家一起讨论一下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))

输出

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

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))

输出

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

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()))

输出

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

4. 使用for循环 + sort

启动for循环以查找唯一的1索引元素

启动了一个嵌套的for循环,将所有具有相同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
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))

输出

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

5. 使用numpy

导入别名np的numpy库。

创建输入列表test_list。

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

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

创建名为result_list的空列表。

对于unique_values中的每个唯一值i,执行以下操作:

a.使用布尔索引来选择arr中第二列等于i的行

b.从选定行的第一列提取值,并将其转换为列表。

c.将结果列表附加到result_list。

打印生成的分组列表。

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)

输出

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

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))

输出

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

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))

输出

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

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)

输出

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

到此这篇关于浅析python中的二元嵌套列表分组的文章就介绍到这了,更多相关python二元嵌套列表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Flask学习之全局异常处理详解

    Flask学习之全局异常处理详解

    Flask是一个基于Python的Web框架,它提供了全局异常处理的机制来捕获和处理应用程序中的异常,下面就带大家深入了解一下Flask是如何实现异常处理的,希望对大家有所帮助
    2023-06-06
  • python自定义函数实现一个数的三次方计算方法

    python自定义函数实现一个数的三次方计算方法

    今天小编就为大家分享一篇python自定义函数实现一个数的三次方计算方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Python使用腾讯云API实现短信验证码功能

    Python使用腾讯云API实现短信验证码功能

    使用Python与腾讯云接口对接,实现短信验证码功能变得非常简单,只需要几行代码就能够轻松实现短信的发送,无须关心复杂的短信协议和底层实现,读者可以根据自己的实际需求,灵活使用腾讯云短信SDK提供的API来实现更丰富的短信功能
    2024-01-01
  • 让文件路径提取变得更简单的Python Path库

    让文件路径提取变得更简单的Python Path库

    这里我们介绍 Python3 自带的库 Path,可以让我们使用更少的代码但是与之而来的是更高的效率,文中有非常详细的介绍及代码示例 ,需要的朋友可以参考下
    2021-05-05
  • python之openpyxl模块的安装和基本用法(excel管理)

    python之openpyxl模块的安装和基本用法(excel管理)

    这篇文章主要给大家介绍了关于python之openpyxl模块的安装和基本用法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • Python logging日志模块使用指南

    Python logging日志模块使用指南

    Python 的 logging 模块提供了标准的日志接口,可以通过它存储各种格式的日志,日志记录提供了一组便利功能,用于简单的日志记录用法,本文就给大家简单的介绍一下Python logging日志模块使用方法,需要的朋友可以参考下
    2023-08-08
  • python中关于requests里的timeout()用法

    python中关于requests里的timeout()用法

    这篇文章主要介绍了python中关于requests里的timeout()用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • 浅谈如何重构冗长的Python代码

    浅谈如何重构冗长的Python代码

    这篇文章主要介绍了浅谈如何重构冗长的Python代码,编写干净的 Pythonic 代码就是尽可能使其易于理解,但又简洁,过长的代码如何做到简洁高效,需要的朋友可以参考下
    2023-04-04
  • 如何利用python多线程爬取天气网站图片并保存

    如何利用python多线程爬取天气网站图片并保存

    最近做个天 气方面的APP需要用到一些天气数据,所以下面这篇文章主要给大家介绍了关于如何利用python多线程爬取天气网站图片并保存的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2021-11-11
  • Python range函数生成一系列连续整数的内部机制解析

    Python range函数生成一系列连续整数的内部机制解析

    这篇文章主要为大家介绍了Python range函数生成一系列连续整数的内部机制解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12

最新评论