Python - 根据关键字将列表拆分为多个列表

Python - Split list to multiple lists with respect to a keyword

我有这个巨大的 python 列表,作为 K 均值聚类算法的输出。这是代码。

clusterlist = []
for i in range(true_k):
clusterlist.append('\nCluster %d:' % i),
for ind in order_centroids[i]:
    clusterlist.append('%s' % terms[ind])

此处,字符串 "Cluster %d" 值在新集群启动时附加到列表中。我想根据关键字 "Cluster" 将这个最终的 clusterlist 分成多个列表,或者它确实可以存储到多个列表而不是单个 clusterlist 中吗?这是示例输出列表:

['\nCluster 0:', 'need', 'zize6kysq2', 'fleming', 'finale', 'finally', 'finals', 'fined', 'finisher', 'firepower', 'fit', 'fitness', 'flaw', 'flaws', 'flexibility', 'ground', 'fluffed', 'fluke', 'fn0uegxgss', 'focussed', 'foot', 'forget', 'forgot', 'form', 'format', 'forward', 'fought', 'final', 'filter', 'figures', 'fight', 'fascinating', 'fashioned', 'fast', 'fastest', 'fat', 'fatigue', 'fault', 'fav', 'featured', 'feel', 'feeling', '\nCluster 1:', 'feels', 'fees', 'feet', 'felt', 'ferguson', 'fewest', 'ffc4pfbvfr', 'ffs', 'field', 'fielder', 'fielders', 'fielding', 'fow', 'fow_hundreds', 'frame', 'gingers', 'gives', 'giving', 'glad', 'glenn', 'gloves', 'god', 'gods', 'goes', 'going', 'gois','\nCluster 2:', 'gon', 'gone', 'good', 'got', 'grand', 'grandhomme', 'grandmom', 'grandpa', 'grass']

import more_itertools as mit
result = list(mit.split_at(clusterlist, pred=lambda x: set(x) & {"Cluster"}))

它给出了以下错误:

ValueError: not enough values to unpack (expected 3, got 1)

请提供解决方案。提前致谢。

迭代解决方案(期望列表以集群项开始):

d = {}
for item in a: 
    if item.startswith("\nCluster"): 
        current_cluster = item[1:-1]  # cut \n and : from cluster name 
        d[current_cluster] = []
    else: 
        d[current_cluster].append(i)

您始终可以使用列表列表来存储集群:

clusterlists = []
for i in range(true_k):
    dummy_list  = []
    for ind in order_centroids[i]:
        dummy_list.append('%s' % terms[ind])
    clusterlists.append(dummy_list)

这里的集群列表将存储集群,您可以通过索引访问它们。