📜  Python – 累积列表拆分

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

Python – 累积列表拆分

有时,在使用字符串列表时,我们可能会遇到一个问题,我们需要执行拆分任务并以累积的方式返回列表的所有拆分实例。此类问题可能发生在涉及数据的许多领域。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是执行此任务的蛮力方式。在此,我们测试列表并在遇到拆分字符时附加列表。

Python3
# Python3 code to demonstrate working of
# Cumulative List Split
# Using loop
 
# initializing list
test_list = ['gfg-is-all-best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Split char
spl_char = "-"
 
# Cumulative List Split
# Using loop
res = []
for sub in test_list:
    for idx in range(len(sub)):
        if sub[idx] == spl_char:
            res.append([ sub[:idx] ])
    res.append([ sub ])
 
# printing result
print("The Cumulative List Splits : " + str(res))


Python3
# Python3 code to demonstrate working of
# Cumulative List Split
# Using accumulate() + join()
from itertools import accumulate
 
# initializing list
test_list = ['gfg-is-all-best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Split char
spl_char = "-"
 
# Cumulative List Split
# Using accumulate() + join()
temp = test_list[0].split(spl_char)
res = list(accumulate(temp, lambda x, y: spl_char.join([x, y])))
 
# printing result
print("The Cumulative List Splits : " + str(res))


输出
The original list is : ['gfg-is-all-best']
The Cumulative List Splits : [['gfg'], ['gfg-is'], ['gfg-is-all'], ['gfg-is-all-best']]


方法#2:使用累积()+连接()
这是解决此问题的单线方法。在此,我们使用accumulate 执行切割成累积的任务,并使用join() 来构造列表的结果列表。

Python3

# Python3 code to demonstrate working of
# Cumulative List Split
# Using accumulate() + join()
from itertools import accumulate
 
# initializing list
test_list = ['gfg-is-all-best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Split char
spl_char = "-"
 
# Cumulative List Split
# Using accumulate() + join()
temp = test_list[0].split(spl_char)
res = list(accumulate(temp, lambda x, y: spl_char.join([x, y])))
 
# printing result
print("The Cumulative List Splits : " + str(res))
输出
The original list is : ['gfg-is-all-best']
The Cumulative List Splits : ['gfg', 'gfg-is', 'gfg-is-all', 'gfg-is-all-best']