【问题标题】:Parsing a string output into python data structures将字符串输出解析为 python 数据结构
【发布时间】:2021-05-03 15:19:05
【问题描述】:

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

partition_ = partition(population)

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

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

B = nx_comm.modularity(F1, [{'3', '4'}, {'1', '2', '5', '6', '7', '8', '9'}])

但由于它是一个字符串,模块化函数不接受它,因为我猜是引号。 谁能帮忙告诉我如何解决这个问题?

提前致谢。

【问题讨论】:

  • 我的猜测是它实际上并没有输出字符串,它只是在控制台上打印出来时转换为字符串。试试B = nx_comm.modularity(F1, partition_)之类的东西?没有更多的上下文很难说。
  • @SumnerEvans 是的,我已经这样做了,但它不接受可变格式。

标签: python string quotes modularity


【解决方案1】:

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

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_)

【讨论】:

  • int 类型不起作用,我有这个错误:ValueError: invalid literal for int() with base 10: '['
  • 你知道nx_comm.modularity()需要什么类型的数据和什么形式的数据吗?
  • 打印输出是: , nx_comm.modularity() 需要类似 [ { ' ' , ' ' , ' '}, { ' ' , ' ' } , { ' ' } ]
  • 哦,好吧,我想我明白了。阅读您的第一个评论回复,您说它卡在'[' 或第一个方括号上。从中我可以收集到整个输出是这样的字符串 "[{'3', '4'}, {'1', '2', '5', '6', '7', '8', '9'}]" 而你写的是这样的集合列表 [{'3', '4'}, {'1', '2', '5', '6', '7', '8', '9'}] 我想我现在明白了这个问题。给我一分钟,我会为你想办法
  • 非常感谢,我已经为此苦苦挣扎了好几天了。
【解决方案2】:

试试这个

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

【讨论】:

  • 不,我不想放这个 [{'3', '4'}, {'1', '2', '5', '6', '7', ' 8', '9'}] 手动,因为我还有 10 个。
  • 所以事实上,当我输入这个: B = nx_comm.modularity(F1, [{'3', '4'}, {'1', '2', '5', ' 6', '7', '8', '9'}]) 它工作得很好,但是当我输入 B = nx_comm.modularity(F1, partition_) 它说 NotAPartition 错误。我认为这是因为 partition_ 的输出类型为 str
  • 写入一个用引号括起来的整数会将其转换为一个字符串,但写入'3' 与输入str(3) 相同
  • 更改 [ int(j) for i in [{'3', '4'}, {'1', '2', '5', '6', '7', ' 8', '9'}] for j in i ] to [str(j) for i in [{'3', '4'}, {'1', '2', '5', '6', '7', '8', '9'}] for j in i ] 然后检查是否正常?
猜你喜欢
  • 2011-04-19
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多