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

新手上路,请多包涵

假设我有以下列表:

 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]]

不完全是我要找的东西。

我也尝试了 这个答案 中的所有选项,但我得到了同样的 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

原文由 Ajay H 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 763
2 个回答

没有任何东西会自动将 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)

原文由 Barmar 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 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))

原文由 Ajax1234 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题