我得到了一个"json parser“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;
};
这就是我所在的位置,这是解析器返回的列表,我希望遍历该列表并创建以下结构:(列表中的最后一个值是我要排序的"position“值)
[['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]]]]
发布于 2019-04-10 08:36:55
对于递归列表处理,您需要确定您正在查看的是列表还是叶:
def test(liste):
if isinstance(liste,list):
for inner_l in liste:
test(inner_l)
else:
print('item: {}'.format(liste))
由于您希望能够定位结构并将其视为一个单元,因此使用helper函数来识别您正在查找的内容可能会有所帮助。您可以使用相同的技术来查找后面跟着单个成员列表的标签的模式:
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样式的嵌套结构。
https://stackoverflow.com/questions/55600666
复制相似问题