📜  Python – 将列表中的连续字符串分组

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

Python – 将列表中的连续字符串分组

给定一个混合列表,任务是编写一个Python程序来对所有连续的字符串进行分组。

Input : test_list = [5, 6, 'g', 'f', 'g', 6, 5, 'i', 's', 8, 'be', 'st', 9]
Output : [5, 6, ['g', 'f', 'g'], 6, 5, ['i', 's'], 8, ['be', 'st'], 9]
Explanation : Strings are grouped to form result.

Input : test_list = [5, 6, 6, 5, 'i', 's', 8, 'be', 'st', 9]
Output : [5, 6, 6, 5, ['i', 's'], 8, ['be', 'st'], 9]
Explanation : Strings are grouped to form result.

方法:使用isinstance() +生成器+ groupby()

在这里,我们使用isinstance()str执行识别字符串的任务, groupby()用于使用isinstance() 对键找到的所有字符串进行分组。构建列表的生成器方式有助于将中间结果转换为列表。

Python3
# Python3 code to demonstrate working of
# Group contiguous strings in List
# Using isinstance() + generator + groupby()
from itertools import groupby
  
# checking string instance
def str_check(ele):
    return isinstance(ele, str)
  
  
def group_strs(test_list):
  
    # grouping list by cont. strings
    for key, grp in groupby(test_list, key=str_check):
        if key:
            yield list(grp)
        else:
            yield from grp
  
  
# initializing list
test_list = [5, 6, 'g', 'f', 'g', 6, 5,
             'i', 's', 8, 'be', 'st', 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# calling recursion fnc.
res = [*group_strs(test_list)]
  
# printing result
print("List after grouping : " + str(res))


输出: