嵌套列表理解以展平嵌套列表

时间:2018-04-16 06:29:31

标签: python

我对Python很陌生,想知道如何使用列表推导来展平下面的嵌套列表,并且还使用条件逻辑。

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

以下内容返回一个嵌套列表,但是当我尝试通过删除内部方括号来展平列表时,我会收到错误。

odds_evens = [['odd' if n % 2 != 0 else 'even' for n in l] for l in nested_list]

4 个答案:

答案 0 :(得分:5)

你的语法有点不对劲。请尝试以下代码段。

nested_list = [[1,2,3], [4,5,6], [7,8,9]]
odds_evens = ['odd' if n % 2 != 0 else 'even' for l in nested_list for n in l]
print(odds_evens)

<强>输出:

['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

Nested List Comprehension

答案 1 :(得分:0)

从嵌套列表中读取数据并根据条件

输出到Flat列表
nested_list = [[1,2,3], [4,5,6], [7,8,9]]

flat_list = [item for sublist in nested_list for item in sublist]
# >>> [1, 2, 3, 4, 5, 6, 7, 8, 9]

flat_list_even = [item for sublist in nested_list for item in sublist if item % 2 == 0]
# >>> [2, 4, 6, 8]


flat_list_odd = [item for sublist in nested_list for item in sublist if item % 2 != 0]
# >>> [1, 3, 5, 7, 9]

flat_list_literal = ["even" if item % 2 == 0 else "odd" for sublist in nested_list for item in sublist]
# >>> ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

答案 2 :(得分:0)

这里有什么问题?

[[2, 1], [4, 6]]
[[4, 3], [8, 8]]
[[3. 2.]
 [6. 7.]]
[[3. 2.]
 [6. 7.]]
[[3 2]
 [6 7]]

答案 3 :(得分:-1)

要创建平面列表,您需要在理解代码中使用一组括号。请尝试以下代码:

odds_evens = ['odd' if n%2!=0 else 'even' for n in l for l in nested_list]

输出:

['odd', 'odd', 'odd', 'even', 'even', 'even', 'odd', 'odd', 'odd']