简体   繁体   English

嵌套列表的C等效项(Python)

[英]C equivalent for nested lists (Python)

I am new to C and trying to learn by comparison with Python. 我是C语言的新手,试图通过与Python的比较来学习。

My question is trivial, but I still need some explanations from experts. 我的问题微不足道,但我仍然需要专家的一些解释。 Here is a Python nested list structure: 这是Python的嵌套列表结构:

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

And here is an interesting piece of code (taken from 'Learning Python' by Lutz) to handle nested structures (sum elements): 这是一段有趣的代码(摘自Lutz的“ Learning Python”),用于处理嵌套结构(求和元素):

def sumtree(L):
    tot = 0
    for x in L:
        if not isinstance(x, list):
            tot += x
        else:
            tot += sumtree(x)
    return tot

If I pass L into this function I will get 36, which is a sum of elements in L. How exactly can nested lists and this particular function be translated into C? 如果将L传递给此函数,我将得到36,这是L中元素的总和。如何将嵌套列表和此特定函数准确地转换为C?

What type is every element of L ? L每个元素是什么类型? It can be a number (an int for example in C), or even a list (it's typical for a list to be implemented with struct s in C). 它可以是一个数字(例如,在C中为int ),甚至可以是一个列表(通常使用C中的struct来实现列表)。

In order to achieve that, you would need a generic list (ie that the data of every node is of type void* ). 为了实现这一点,您将需要一个通用列表(即,每个节点的数据都为void*类型)。 Notice that C doesn't provide a list from the standard library, you have to write one (here is an example ). 注意,C没有提供标准库中的列表,您必须编写一个列表(这里是一个示例 )。

Then, in order to get the sum, you would do something like that: 然后,为了获得总和,您需要执行以下操作:

int sumtree(struct listnode * L) {
    int tot = 0;
    while (L != NULL) {
        if(L.data /* TODO: check if it is a number*/)
            tot += L.data;
        else /* L.data is a sublist */
            tot = sumtree(L.data);
        list = list->next;
    }
    return tot;
}

In order to get the type, you need to follow this answer: How do I check if a variable is of a certain type (compare two types) in C? 为了获得类型,您需要遵循以下答案: 如何在C中检查变量是否属于某种类型(比较两种类型)?

However, such nested lists in C are not common, and I would advise you to re-approach the issue. 但是,在C中这种嵌套列表并不常见,我建议您重新解决该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM