【问题标题】:How transform list=[1,2,[3,4],[5,6],7,[8,9,10]] in list1=[1,2,3,4,5,6,7,8,9,10] in python? [duplicate]如何在 list1=[1,2,3,4,5,6,7,8 中变换 list=[1,2,[3,4],[5,6],7,[8,9,10]] ,9,10] 在 python 中? [复制]
【发布时间】:2023-03-25 14:32:01
【问题描述】:

我需要将列表转换为“正常”列表

list=[1,2,[3,4],[5,6],7,[8,9,10]]

list=[1,2,3,4,5,6,7,8,9,10]

【问题讨论】:

  • 我相信这个答案只适用于列表列表,这个问题是一个数字和列表的列表。

标签: python list transform


【解决方案1】:

这是我的答案。首先,不要将您的列表称为“列表”。这使我们无法使用此答案所需的内置列表关键字。

import collections
from itertools import chain

#input list called l
l = [1,2,[3,4],[5,6],7,[8,9,10]]

#if an item in the list is not already a list (iterable) then put it in one. 
a = [i if isinstance(i, collections.Iterable) else [i,] for i in l]

#flattens out a list of iterators
b = list(chain.from_iterable(a))

print b
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

【讨论】:

    【解决方案2】:

    两种方式:

    items = [1,2,[3,4],[5,6],7,[8,9,10]]
    new_list = []
    [new_list.extend(x) if type(x) is list else new_list.append(x) for x in items]
    print new_list
    

    new_list2 = []
    for item in items:
        if type(item) is list:
            new_list2.extend(item)
        else:
            new_list2.append(item)
    
    print new_list2
    

    【讨论】:

    • 谢谢很好......工作
    猜你喜欢
    • 2020-10-15
    • 1970-01-01
    • 2022-10-14
    • 2011-10-30
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多