【问题标题】:Python: Parsing in a nested list of numbers through command promptPython:通过命令提示符解析嵌套的数字列表
【发布时间】:2019-05-05 11:27:15
【问题描述】:

我正在尝试编写一个 python 程序 (rec_list_sum.py),它递归地查找嵌套数字列表的总和。

我对 Powershell 终端的输入:

python rec_list_sum.py [1,2,3,[4,5],[6,7],8]

我的函数接受这样的数组:

import sys

def recursive_list_sum(array):

    total = 0

    for ele in array:
        if isinstance(ele, list):
            total = total + recursive_list_sum(ele)
        else:
            total = total + ele

    return total

这是我有问题的部分,解析输入:

if __name__ == "__main__":
    string = sys.argv[1]
    digits = [int(i) for i in str(string)]
    ans = recursive_list_sum(digits)

    print(ans)

我的代码可以在 jupyter 笔记本上运行,但我似乎无法使用 PowerShell 将此输入解析为 python。谁能解释一下?

【问题讨论】:

  • 相信我,我已经浏览了该网站上的现有帖子,但没有一个涉及解析嵌套的数字列表。
  • 如果你是唯一会使用它的人,你可以使用 eval。 digits = eval(string)

标签: python list recursion nested numbers


【解决方案1】:

您可以使用ast.literal_eval 将输入字符串解析为 Python 表达式:

from ast import literal_eval
ans = recursive_list_sum(literal_eval(sys.argv[1]))

【讨论】:

  • 成功了,谢谢!除了导入 ast 之外,还有其他方法吗?
  • 很高兴能提供帮助。您可以参考我的其他答案,了解如何自己解析输入的示例。
【解决方案2】:

你可以这样写解析器:

def parse(s):
    def _parse(s):
        output = []
        index = 0
        num = ''
        while index < len(s):
            char = s[index]
            index += 1
            if char.isdigit():
                num += char
            if char in ',]' and num:
                output.append(int(num))
                num = ''
            if char == '[':
                sublist, offset = _parse(s[index:])
                output.append(sublist)
                index += offset
            elif char == ']':
                break
        return output, index
    return _parse(s)[0][0]

这样:

parse('[1,2,3,[4,5],[6,7],8]')

返回:

[1, 2, 3, [4, 5], [6, 7], 8]

【讨论】:

    【解决方案3】:

    你可以使用带有方法loads()的json库

    import json
    ans = json.loads(sys.argv[1])
    

    ans 将是一个可以正常迭代的列表类型

     >>> type(json.loads(ans))
     <class 'list'>
    

    【讨论】:

      猜你喜欢
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2021-05-15
      • 1970-01-01
      相关资源
      最近更新 更多