首页 > 解决方案 > 为什么我的列表变成了一个 int 以及如何解决它

问题描述

我遇到了以下代码的问题:

def foo():
    return 1,"str",3,4

def bar():
    return 5

    lst_c1 = []
    lst_c2 = []
    lst_c1 = foo()
    lst_c2 = bar()
    print(type(lst_c2))
    lst_p = lst_c1 + lst_c2
    print(lst_p)

我想将两个列表合并为一个,但出现以下错误:

    lst_p = lst_c1 + lst_c2
TypeError: can only concatenate tuple (not "int") to tuple

首先,为什么当我声明 lst_c1 = [] 它具有元组类型时,它不应该是一个列表吗?然后,为什么带有单个项目的列表(或明显的元组)不被视为元组或列表。我想当你使用 '=' 时,它会改变类型,但这是否可以通过方法来保持 lst_c2 的类型?

lst_c2 =bar()

谢谢

标签: python-2.7

解决方案


如果您希望能够连接这两者,只需将其更改bar()为:

def bar():
    return 5,

这样,它将返回一个tuple,与 相同foo()


推荐阅读