如何将一个列表分成多个子列表?

3

我正在尝试将列表中的第一个元素[CS-PP-GE-RI-ET]转换为:

[CS]
[CS-PP]
[CS-PP-GE]
[CS-PP-GE-RI]
[CS-PP-GE-RI-ET]

这是我目前的进展:
data = ['CS-PP-GE-RI-ET',
        'CS-PP-ET-GE',
        'CS-PP-ET-GE-BD',
        'CS-PP-ET-GE',
        'CS-PP-ET-CD-PI-GE']

word0 = []
word1 = []
for i in range(len(data)):
    # print(i)  # 0 1 2 3 4 ... however many elements are in data
    split = data[i].split('-')  # prints CS-PP-GE-RI-ET ...
    # print(split)  # this prints ['CS', 'PP', 'GE', 'RI', 'ET'] for each element
    for j in range(len(split)-1):  # you have to use range(len()-1 to iterate all the way to the end of the index count
        # print(split[j])  # this prints each element CS PP GE RI ET CS PP ...
        # word1.append(split[j])
        temp0 = split[j]
        word0.append(temp0)
        temp1 = split[j + 1]
        temp3 = temp0 + '-' + temp1
        word0.append((temp3))

    print(word0)

这是我得到的结果:
['CS', 'CS-PP', 'PP', 'PP-GE', 'GE', 'GE-RI', 'RI', 'RI-ET']
['CS', 'CS-PP', 'PP', 'PP-GE', 'GE', 'GE-RI', 'RI', 'RI-ET', 'CS', 'CS-PP', 'PP', 'PP-ET', 'ET', 'ET-GE']
...

我知道我缺乏strappend()的基本理解,但似乎无法弄清楚。

最终结果应该是:

[CS]
[CS-PP]
[CS-PP-GE]
[CS-PP-GE-RI]
[CS-PP-GE-RI-ET]
[CS]
[CS-PP]
[CS-PP-ET]
[CS-PP-ET-GE]
[CS]
...

感谢您的帮助。
3个回答

1
我们可以在这里使用 itertools.accumulate
from itertools import accumulate

l = 'CS-PP-GE-RI-ET'.split('-')
print(*accumulate(l, lambda x, y: '-'.join([x, y])), sep='\n')

CS
CS-PP
CS-PP-GE
CS-PP-GE-RI
CS-PP-GE-RI-ET

一个通用的解决方案是:

data = ['CS-PP-GE-RI-ET',
        'CS-PP-ET-GE',
        'CS-PP-ET-GE-BD',
        'CS-PP-ET-GE',
        'CS-PP-ET-CD-PI-GE']

def acc(s):
    l = s.split('-')
    func = lambda x, y: '-'.join([x, y])
    return '\n'.join(accumulate(l, func))

print(*map(acc, data), sep='\n\n')

CS
CS-PP
CS-PP-GE
CS-PP-GE-RI
CS-PP-GE-RI-ET

CS
CS-PP
CS-PP-ET
CS-PP-ET-GE

CS
CS-PP
CS-PP-ET
CS-PP-ET-GE
CS-PP-ET-GE-BD

CS
CS-PP
CS-PP-ET
CS-PP-ET-GE

CS
CS-PP
CS-PP-ET
CS-PP-ET-CD
CS-PP-ET-CD-PI
CS-PP-ET-CD-PI-GE

这个解决方案没有意义。如果变量 l 是数据,那么它只会打印出原始列表。 - charlesreid1
此解决方案将 l 视为 OP @charlesreid1 给出的初始状态。 - yatu
这个脚本的输出只是 CS-PP-GE-RI-ET - charlesreid1
1
@yatu 抱歉,我误读了输出。谢谢!我会学习itertools,它看起来非常有用。 - MasoodQaim
很高兴能帮到你,@MasoodQaim。 - yatu
显示剩余3条评论

1
这将把您的所有项目写入一个包含列表的列表中,因为您的列表需要一个占位符。
wrapper_list = list()
my_list = ['CS-PP-GE-RI-ET']
for str_item in my_list:
    temp_string = ""
    combined_string_list = list(str_item.split('-'))
    for index in range(len(str_item)):
         wrapper_list.append(["-".join(combined_string_list[0:index+1])])
print(wrapper_list)  

1

你也可以这样做:

for word in data:
    for i in range(len(word)):
        if word[i] == '-':
            print([ word[:i] ])
    print([ word ])

或者使用列表推导式:

print( '\n'.join( str([ word[:i] ]) 
                  for word in data
                  for i in range(len(word))
                  if word[i] == '-' or i == len(word) - 1 ) )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接