📜  Python|按字符串大小对给定列表进行分类

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

Python|按字符串大小对给定列表进行分类

有时,我们有一个用例,我们需要按各种因素(如首字母或任何其他因素)对字符串进行分组。这些类型的问题是数据库查询的典型问题,因此可能在编程时发生在 Web 开发中。本文重点介绍一种按字符串大小进行的分组。让我们讨论可以执行此操作的某些方式。

方法 #1:使用next() + lambda + 循环

以上3个函数的组合用于以朴素的方法解决这个特定问题。 lambda函数执行查找相似长度的任务,而 next函数有助于向前迭代。

# Python3 code to demonstrate
# Categorize by string size 
# using next() + lambda + loop
  
# initializing list
test_list = ['man', 'a', 'geek', 'for', 'b', 'free']
  
# printing original list
print("The original list : " + str(test_list))
  
# using next() + lambda + loop
# Categorize by string size 
util_func = lambda x, y: len(x) == len(y)
res = []
for sub in test_list:
    ele = next((x for x in res if util_func(sub, x[0])), [])
    if ele == []:
        res.append(ele)
    ele.append(sub)
  
# print result
print("The list after Categorization : " + str(res))
输出 :
The original list : ['man', 'a', 'geek', 'for', 'b', 'free']
The list after Categorization : [['man', 'for'], ['a', 'b'], ['geek', 'free']]

方法 #2:使用sorted() + groupby()

这个特定的任务也可以使用 groupby函数来解决,它提供了一种方便的方法来解决这个问题。 sorted函数按大小对元素进行排序,以提供给 groupby 以进行相关分组。

# Python3 code to demonstrate
# Categorize by string size 
# using sorted() + groupby()
from itertools import groupby
  
# initializing list
test_list = ['man', 'a', 'geek', 'for', 'b', 'free']
  
# printing original list
print("The original list : " + str(test_list))
  
# using sorted() + groupby()
# Categorize by string size 
util_func = lambda x: len(x)
temp = sorted(test_list, key = util_func)
res = [list(ele) for i, ele in groupby(temp, util_func)]
  
# print result
print("The list after Categorization : " + str(res))
输出 :
The original list : ['man', 'a', 'geek', 'for', 'b', 'free']
The list after Categorization : [['a', 'b'], ['man', 'for'], ['geek', 'free']]