Search code examples
python-3.xlistsplitk-meansdata-mining

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


I have this huge python list I got as an output from a K means Clustering algorithm. Here is the code.

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

Here , the string "Cluster %d" value is appended to the list when a new cluster starts. I want to split this final clusterlist into mutiple lists based on the keyword "Cluster" or can it be indeed stored into multiple lists rather than a single clusterlist ?. Here is the sample output list:

['\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']

I tried this SO solution using the following code but it didn't work.

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

It gave the following error:

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

Please provide a solution. Thanks in advance.


Solution

  • You can always use list of lists to store the clusters:

    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)
    

    Here the clusterlists will store clusters and you can reach them with indices.