【问题标题】:Calling local variable causes TypeError: cannot unpack non-iterable NoneType object调用局部变量导致 TypeError: cannot unpack non-iterable NoneType object
【发布时间】:2020-09-30 17:17:33
【问题描述】:

嗨,我想知道是否可以帮助我理解为什么我的自定义函数可以工作并给出我想要的输出,但是当我尝试在函数之外为它分配变量时(调用标题和行分开)我得到:

header,rows = parse_tsv(path) TypeError: cannot unpack non-iterable NoneType object

这是我的代码:

def parse_tsv(path):
    with open(path) as infile:

        header = []
        for line in infile:
            line = line.strip()
            header.append(line.split("\t")) 
            header = header[0]
            break

        rows = []
        for line in infile:
            line = line.strip()
            rows.append(line.split("\t"))
            if not line:
                continue
        rows = [[int(x) if x.isdigit() else x for x in i] for i in rows]
        rows = rows[1:]

    return print('header','=',header,'\n''rows','=',rows)

header,rows = parse_tsv(path)

header

我不明白为什么它会使用 parser_tsv(path) 为我提供正常运行且正确的输出,但 header,rows 不起作用。我不认为它可以分裂它们,但我不确定如何解决这个问题。感谢您的宝贵时间!

【问题讨论】:

  • 分离printreturn: ``` print('header','=',header,'\n''rows','=',rows) 返回头,行```

标签: python-3.x typeerror


【解决方案1】:

那是因为您正在返回print 的输出(始终为None)。只需返回 header, rows 即可。

【讨论】:

  • 很高兴听到!非常欢迎您接受正确的答案:)
【解决方案2】:

您当前正在调用该函数以返回 2 个值 (header, rows),但该函数仅返回 1。

它们必须匹配。

如果您决定返回 2 个值,您实际上是在返回一个元组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 2021-09-24
    • 2020-08-26
    • 2021-01-27
    • 2022-01-05
    • 2023-01-04
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多