将字符串输出解析为python数据结构

问题描述

我有这个返回字符串变量的函数:

partition_ = partition(population)

这个输出: "[{'3','4'},{'1','2','5','6','7','8','9'}]"

我想将此输出分配给此函数:

B = nx_comm.modularity(F1,[{'3','9'}])

但是因为它是一个字符串,所以模块化函数不接受它,因为我猜是引号。 任何人都可以请帮助告诉我我该如何解决这个问题?

提前致谢。

解决方法

您需要的是将输出字符串解析为您想要的格式的函数。这是我制作的一个简单的解析器,它可以创建您需要的输出。让我知道它是否有效。

partition_ = "[{'3','4'},{'1','2','5','6','7','8','9'}]"


def custom_parser(string):

    list_of_sets = []

    temp = []

    begin_set = False

    for char in string:

        if begin_set:

            if char == '}':

                begin_set = False

                temp2 = set(temp)

                list_of_sets.append(temp2)

                temp = []

            elif char not in ['\'',',' ']:

                temp.append(char)

        if char == '{':

            begin_set = True

    return list_of_sets


new_partition_ = custom_parser(partition_)
,

试试这个

B = nx_comm.modularity(F1,[int(j)  for i in partition_ for j in i ])

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...