Python如何根据长度将字符串列表拆分为子列表?

2021年3月23日15:20:35 发表评论 882 次浏览

给定一个字符串列表, 编写一个Python程序, 根据字符串长度将列表分为多个子列表。

例子:

Input : ['The', 'art', 'of', 'programming']
Output : [['of'], ['The', 'art'], ['programming']]

Input : ['Welcome', 'to', 'lsbin']
Output : [['to'], ['Welcome'], ['lsbin']]

方法1:Pythonic天真

上述方法的幼稚方法使用字典和for循环遍历列表。在每次迭代中, 它都会检查元素长度是否已经在列表中。如果没有, 它将元素长度和元素添加为核心价值对, 否则, 该元素仅添加到值子列表中。最后, 我们列出dict的所有值并返回。

# Python3 program to Divide list of strings 
# into sublists based on string length
  
def divideList(lst):
     dct = {}
  
     for element in lst:
         if len (element) not in dct:
             dct[ len (element)] = [element]
         elif len (element) in dct:
             dct[ len (element)] + = [element]
      
     res = []
     for key in sorted (dct):
         res.append(dct[key])
      
     return res
      
# Driver code
lst = [ 'The' , 'art' , 'of' , 'programming' ]
print (divideList(lst))

输出如下:

[['of'], ['The', 'art'], ['programming']]

方法2:

defaultdict()

来自收藏模块

该方法使用defaultdict并将其保存在变量" group_by_len"中。使用for循环, 我们将字符串的长度保存为键, 并将键长度的字符串保存为其值。最后, 我们列出" group_by_len"的所有值并返回。

# Python3 program to Divide list of strings 
# into sublists based on string length
from collections import defaultdict
  
def divideList(lst):
     group_by_len = defaultdict( list )
     for ele in lst:
         group_by_len[ len (ele)].append(ele)
          
     res = []
     for key in sorted (group_by_len):
         res.append(group_by_len[key])
          
     return res
      
# Driver code
lst = [ 'The' , 'art' , 'of' , 'programming' ]
print (divideList(lst))

输出如下:

[['of'], ['The', 'art'], ['programming']]

方法3:

通过...分组()

itertools

模组

解决给定问题的最有效, 最简单的方法是使用通过...分组()从itertools模块。这是一种单行代码, 其中我们使用两个变量" l"(长度)和" g"(字符串组)遍历" lst", 按长度分组, 最后返回包装在列表中的所有分组。

# Python3 program to Divide list of strings 
# into sub lists based on string length
from itertools import groupby
  
def divideList(lst):
     res = dict ((l, list (g)) for l, g in groupby(lst, key = len ))
  
     # Sorting dict by key
     res = sorted (res.items(), key = lambda kv:(kv[ 0 ], kv[ 1 ]))
  
     # Removing key from list of tuple
     return [el[ 1 :] for el in ( tuple (x) for x in res)]
      
# Driver code
lst = [ 'The' , 'art' , 'of' , 'programming' ]
print (divideList(lst))

输出如下:

[(['of'], ), (['The', 'art'], ), (['programming'], )]

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: