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

时间:2017-10-01 21:30:06

标签: python python-3.x list

说我有以下列表:

a = 1
b = [2,3]
c = [4,5,6]

我想将它们连接起来,以便得到以下内容:

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

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

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

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

>>> [a]+[b]+[c]
[1, [2, 3], [4, 5, 6]]

不是我想要的。

我还尝试了this answer中的所有选项,但我得到了上面提到的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

它应该很简单,但没有任何内容适用于a。有没有办法做到这一点有效?它确实必须是 pythonic

3 个答案:

答案 0 :(得分:4)

没有什么会自动将int视为一个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])

如果你经常这样做,你可能想写一个函数:

def as_list(x):
    if type(x) is list:
        return x
    else:
        return [x]

然后你可以写:

as_list(a) + as_list(b) + as_list(c)

答案 1 :(得分:1)

您可以使用itertools

from itertools import chain

a = 1
b = [2,3]
c = [4,5,6]
final_list = list(chain.from_iterable([[a], b, c]))

输出:

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

但是,如果您提前不知道abc的内容,可以试试这个:

new_list = [[i] if not isinstance(i, list) else i for i in [a, b, c]]
final_list = list(chain.from_iterable(new_list))

答案 2 :(得分:0)

接受的答案是最好的方法。添加另一个变体。评论中也有解释。

from collections.abc import Iterable


a = "fun" 
b = [2,3]
c = [4,5,6]


def flatten(lst):
    for item in lst:
        if isinstance(item,Iterable) and not isinstance(item,str): # checking if Iterable and taking care of strings as well
            yield from flatten(item)
        else:
            yield item

# test case:

res = []
res.extend([a]+[b]+[c]) # casting them into lists,  [a]+[b]+[c] [1, [2, 3], [4, 5, 6]]
print(list(flatten(res)))

生产

['fun', 2, 3, 4, 5, 6]

[Program finished] 
相关问题