Python 根据字符串大小对给定列表进行分类
我们考虑一个包含许多不同长度的字符串的列表。在本文中,我们将了解如何将这些元素分组,其中每组中的字符串长度相等。
用 for 循环
我们设计了一个 for 循环,它将遍历列表中的每个元素,并且仅当其长度与现有元素的长度相匹配时才将其传给列表。
示例
listA = ['Monday','Thursday','Friday','Saturday','Sunday']
# Given list
print("Given list : \n",listA)
# Categorize by string size
len_comp = lambda x, y: len(x) == len(y)
res = []
for sub_list in listA:
ele = next((i for i in res if len_comp(sub_list, i[0])), [])
if ele == []:
res.append(ele)
ele.append(sub_list)
# Result
print("The list after creating categories : \n",res)输出
运行上述代码,将得到以下结果 −
Given list : ['Monday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] The list after creating categories : [['Monday', 'Friday', 'Sunday'], ['Thursday', 'Saturday']]
用 sort 和 groupby
此方法中,我们首先按元素长度对所有元素进行排序,然后应用作为 itertools 模块一部分的 group by 函数。
示例
from itertools import groupby
listA = ['Monday','Thursday','Friday','Saturday','Sunday']
# Given list
print("Given list : \n",listA)
# Categorize by string size
get_len = lambda x: len(x)
sub_list = sorted(listA, key = get_len)
res = [list(ele) for i, ele in groupby(sub_list, get_len)]
# Result
print("The list after creating categories : \n",res)输出
运行上述代码,将得到以下结果 −
Given list : ['Monday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] The list after creating categories : [['Monday', 'Friday', 'Sunday'], ['Thursday', 'Saturday']]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP