python-将单个整数转换为列表

Aja*_*y H 2 python list python-3.x

说我有以下列表:

a = 1
b = [2,3]
c = [4,5,6]
Run Code Online (Sandbox Code Playgroud)

我想将它们串联起来,从而得到以下信息:

[1,2,3,4,5,6]
Run Code Online (Sandbox Code Playgroud)

我尝试了通常的+运算符:

>>> a+b+c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Run Code Online (Sandbox Code Playgroud)

这是因为该a术语。它只是一个整数。所以我将所有内容都转换为列表:

>>> [a]+[b]+[c]
[1, [2, 3], [4, 5, 6]]
Run Code Online (Sandbox Code Playgroud)

并不是我想要的。

我也尝试了此答案中的所有选项,但遇到了上述相同的int错误。

>>> l = [a]+[b]+[c]
>>> flat_list = [item for sublist in l for item in sublist]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
TypeError: 'int' object is not iterable
Run Code Online (Sandbox Code Playgroud)

它应该足够简单,但是该术语没有任何用处a。有什么办法可以有效地做到这一点?它好好尝试一下一定是Python的

Bar*_*mar 6

没有什么可以自动将a int视为一个list int。您需要检查该值是否为列表:

(a if type(a) is list else [a]) + (b if type(b) is list else [b]) + (c if type(c) is list else [c])
Run Code Online (Sandbox Code Playgroud)

如果必须经常执行此操作,则可能需要编写一个函数:

def as_list(x):
    if type(x) is list:
        return x
    else:
        return [x]
Run Code Online (Sandbox Code Playgroud)

然后您可以编写:

as_list(a) + as_list(b) + as_list(c)
Run Code Online (Sandbox Code Playgroud)