Python内联列表递归

时间:2014-02-05 20:46:17

标签: python recursion

我想对列表进行递归读取

例如,我有以下内容:

[x if x % 2 == 0 else [a for a in [9,8,7]] for x in [2,3,4,5]]

输出是:

[2, [9, 8, 7], 4, [9, 8, 7]]

但我希望它是:

[2, 9, 8, 7, 4, 9, 8, 7]

有可能吗?

我试过

[x if x % 2 == 0 else a for a in [9,8,7] for x in [2,3,4,5]]

并没有奏效[2, 9, 4, 9, 2, 8, 4, 8, 2, 7, 4, 7]

提前致谢。

2 个答案:

答案 0 :(得分:2)

或没有itertools:

a = [[x] if x % 2 == 0 else [a for a in [9,8,7]] for x in [2,3,4,5]]
a = [i for x in a for i in x]
print (a)

答案 1 :(得分:1)

itertools负责照顾:

from collections import Iterable
from itertools import chain

t =  [x if x % 2 == 0 else [a for a in [9,8,7]] for x in [2,3,4,5]]
final_list = list(chain.from_iterable(item if isinstance(item,Iterable) and
                    not isinstance(item, basestring) else [item] for item in t))
print(final_list)

来源:flatten list of list through list comprehension

编辑:以前的解决方案的问题是它只适用于数值相同的数组(例如[[1,2], [3,4]]),而像[5, [1,2], [3,4]]这样的数组返回一些链对象,因为值为不同的级别(即5)。