![](/img/trans.png)
[英]How do I convert a nested tuple of tuples and lists to lists of lists in Python?
[英]How do I convert nested python lists to c structures?
我已經獲得了一個“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]]]]
對於遞歸列表處理,您需要確定您正在查看的是列表還是葉子:
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風格的嵌套結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.