python - 如何在 isinstance (object,list) 中打印列表

标签 python list

我需要帮助。你能解释一下“if not isinstance(front, list):”行中 list 的值吗?我试图找到它的答案。我是 python 新手。

def sumtree(L):                         # Breadth-first, explicit queue
    tot = 0
    items = list(L)                     # Start with copy of top level
    print('items :',items)
    while items:
        front = items.pop(0)            # Fetch/delete front item
        print('Front:',front)
        print('list:',items)
        print(isinstance(front, list))
        if not isinstance(front, list):
            print('tot in if:',tot)
            tot += front                # Add numbers directly
            print('tot',tot)
        else:
            items.extend(front)         # <== Append all in nested list
            print('inside:',items)
    return tot


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

最佳答案

让我们看看您的示例输入:

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

这是一个包含 4 个元素的列表:

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

当你调用sumtree(L)时,front的第一个值将是1,它不是一个列表,所以 >if 子句将执行。在第二次迭代中,front 将获得 [2, [3, 4], 5],它是一个列表,因此 else 子句将执行。代码中的 print() 语句将准确显示正在发生的情况。你应该验证我到目前为止所说的是否正确。您可以从那里跟踪其余的执行。

关于python - 如何在 isinstance (object,list) 中打印列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212891/

相关文章:

Python->数据框->扩展数据框

python - Numpy 高精度

java - 检查来自另一个 java 类的登录系统的列表元素

python - 将整数转换为数字列表

python - 在 Python 中使用列表运行减法

Python - 始终将某些字符串附加到列表的末尾

python - 当数据格式为 "NCHW"时,如何在tensorboard中显示图像?

Python:获取多维列表中的所有对和对的频率

python - if substring in string,当子串有多个值时

java - 如何实现排序列表