【问题标题】:python - Convert Single integer into a listpython - 将单个整数转换为列表
【发布时间】:2017-10-01 21:30:06
【问题描述】:

假设我有以下列表:

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

【问题讨论】:

  • 问题:为什么一开始就有不一致的数据类型?为什么不对所有变量一致地使用列表?
  • 我的问题没这么简单。它是我不断更新列表值的函数的一部分(具有可变长度的列表列表)。如果我把它都写在这里会很乱。但这是基本错误。

标签: python python-3.x list


【解决方案1】:

没有什么会自动将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)

【讨论】:

  • 我实际上是在运行 a+b+c 以获取更改大小的列表。我只考虑了a。但在某些时候,甚至 c 也变成了 1 个整数。从你的功能中得到。谢谢
  • 您是否要解决问题以获得正确的 a 值?
【解决方案2】:

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

【讨论】:

  • 这是否适用于a = 1,这显然是他的真实情况?
【解决方案3】:

接受的答案是最好的方法。添加另一个变体。 cmets 中的解释也是如此。

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] 

【讨论】:

    猜你喜欢
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2015-06-02
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多