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

问题描述 投票:2回答:2

我正在尝试将列表中的第一个元素[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]
...

感谢您的帮助。

python string list append
2个回答
0
投票

这里是一个基于itertools的人:

itertools

-2
投票
from itertools import accumulate
l = ['CS-PP-GE-RI-ET']
l = l[0].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
© www.soinside.com 2019 - 2024. All rights reserved.