如何将嵌套的python列表转换为c结构?

问题描述 投票:0回答:1

我已经获得了一个“json解析器”python模块,它解析json文件并从json文件返回结构列表。我被要求编写一个python模块,它接受这个列表并将其转换为填充了c结构的“.h”文件。我的问题是json文件可以包含许多嵌套列表(意味着嵌套列表中的嵌套列表等),我似乎无法获得正确的代码来访问这些。此外,这些列表中的每个元素都有一个名为“position”的键值对,我希望能够在这个键值对之后对结构进行排序,并创建一个带有排序结构的“.h”文件,但我不确定是否我的代码将成功。

我的想法是创建一个遍历列表的for循环,如果它找到该列表中的另一个列表,则检查此嵌套列表以获取更多嵌套列表等。我是python的新手,我可以用递归函数解决这个问题吗?如果是这样,怎么样?

遍历列表的方法(仅适用于第一个列表中的嵌套列表)

def test(liste):
        for inner_l in liste:
            for item in inner_l:
                print(item)

我的排序功能

def takeFourth(elem):
        return elem[3]

neueListe = neueListe + x.sort(key=takeFourth)

预期的结果,最终的.h文件应如下所示:

struct SubStructOfSubStruct
{
    int MyInteger;
};

struct ThirdSubStructType
{
    float MyFloatValue;
    double MyDoubleValue;
    struct SubStructOfSubStructType SubStructOfSubStruct;
};

struct SubStructType
{
    float MyFloatValue;
    double MyDoubleValue;
};

struct SecondSubStructType
{
    int MyInteger;
};

struct Toplevel
{
    struct ThirdSubStructType ThirdSubStruct;
    struct SubStructType SubStruct;
    char MyString[10];
    boolean MyBoolValue;
    double MyDoubleValue;
    float MyFloatValue;
    int MyInteger;
    struct SecondSubStructType SecondSubStruct;
};

这就是im at,这是解析器返回的列表,我想要通过它创建结构:(列表中的最后一个值是我想要排序的“位置”值)

[['SubStructOfSubStructType ', [['Integer', 'MyInteger', 33, 0]]], 
['ThirdSubStructType ', [['TreeNode', 'SubStructOfSubStructType', 'SubStructOfSubStruct', 2], ['Double', 'MyDoubleValue', 100, 0], ['Float', 'MyFloatValue', 22, 1]]], 
['SecondSubStructType', [['Integer', 'MyInteger', 333, 0]]], 
['SubStructType', [['Double', 'MyDoubleValue', 1000, 0], ['Float', 'MyFloatValue', 222, 1]]], 
['Toplevel', [['TreeNode', 'ThirdSubStructType', 'ThirdSubStruct', 7], ['Float', 'MyFloatValue', 2, 1], ['Boolean', 'MyBoolValue', False, 2], ['Double', 'MyDoubleValue', 10, 0], ['Integer', 'MyInteger', 3, 3], ['TreeNode', 'SecondSubStructType', 'SecondSubStruct', 6], ['String', 'MyString', 'Leer', 4], ['TreeNode', 'SubStructType','SubStruct',5]]]]
python c list structure
1个回答
0
投票

对于递归列表处理,您需要确定您正在查看的是列表还是叶子:

def test(liste):
    if isinstance(liste,list):
        for inner_l in liste:
            test(inner_l)
    else:
        print('item: {}'.format(liste))

由于您希望能够定位结构并将它们视为一个单元,因此使用辅助函数来识别您正在寻找的内容可能会有所帮助。您可以使用相同的技术查找标签的模式,后跟单个成员列表:

def is_struct(liste):
    return not isinstance(liste[0],list) and isinstance(liste[1],list) and len(liste) == 2

然后你可以把它们放在一起:

def test(liste):
    if isinstance(liste,list):
        if is_struct(liste):
            print('struct {}'.format(liste[0]))
            for item in liste[1]:
                print('  var: {}'.format(item))
        else:
            for inner_l in liste:
                test(inner_l)
    else:
        print('unexpected: {}'.format(liste))

此技术应处理任意嵌套的列表结构。您可以扩展它以处理C风格的嵌套结构。

© www.soinside.com 2019 - 2024. All rights reserved.