【问题标题】:Python - Split list to multiple lists with respect to a keywordPython - 根据关键字将列表拆分为多个列表
【发布时间】:2020-10-07 12:04:24
【问题描述】:

我有一个巨大的 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”将这个最终的集群列表拆分为多个列表,或者它是否可以确实存储到多个列表而不是单个集群列表中?这是示例输出列表:

['\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"}))

它给出了以下错误:

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

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

【问题讨论】:

  • 预期输出是什么,您的最终result 列表应该是什么样子?请提供预期输出

标签: python-3.x list split k-means data-mining


【解决方案1】:

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

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)

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

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多