如何在list1中变换列表= [1,2,[3,4],[5,6],7,[8,9,10]] = [1,2,3,4,5,6,7,8 ,9,10]在python中?

时间:2015-11-22 22:46:17

标签: python list transform

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

列表= [1,2,[3,4],[5,6],第7,[8,9,10]]

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

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

两种方式:

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