迭代 python 个嵌套列表
iteration over python nested lists
我需要将列表 'a' 转换为列表 'b' ,
怎么做?
a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = [[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12,]]]
您可以使用列表理解:这假设您在每个子列表中只有两个子子列表。既然你的输入输出都非常清楚,那它就如你所愿
a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = [[c[0] + c[1]] for c in a ]
print (b)
输出
[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
您可以使用 sum()
的巧妙技巧来加入嵌套列表:
[[sum(l, [])] for l in a]
#[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
为了更清楚地说明为什么这样做,请考虑以下示例:
>>> sum([[1,2], [3,4]], [])
[1, 2, 3, 4]
或者您可以使用更高效的 itertools.chain_from_iterable
方法:
flatten = itertools.chain.from_iterable
[[list(flatten(l))] for l in a]
#[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
我建议以下列表理解:
In [1]: a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
...:
In [2]: [[[a for sub in nested for a in sub]] for nested in a]
Out[2]: [[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
相当于下面的嵌套for循环:
result = []
for nested in a:
_temp = []
for sub in nested:
for a in sub:
_temp.append(a)
result.append([_temp])
不过,我更愿意这样写:
result = []
for nested in a:
_temp = []
for sub in nested:
_temp.extend(sub)
result.append([_temp])
实现两个列表串联的另一种方法如下:
a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = list(map(lambda elem: [[*elem[0], *elem[1]]],a))
print(b)
输出:
[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
我建议使用循环方法。
a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = []
for i in a:
new_j = []
for j in i:
new_j.extend(j)
new_i = [new_j]
b = b + [new_i]
b
我需要将列表 'a' 转换为列表 'b' , 怎么做?
a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = [[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12,]]]
您可以使用列表理解:这假设您在每个子列表中只有两个子子列表。既然你的输入输出都非常清楚,那它就如你所愿
a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = [[c[0] + c[1]] for c in a ]
print (b)
输出
[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
您可以使用 sum()
的巧妙技巧来加入嵌套列表:
[[sum(l, [])] for l in a]
#[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
为了更清楚地说明为什么这样做,请考虑以下示例:
>>> sum([[1,2], [3,4]], [])
[1, 2, 3, 4]
或者您可以使用更高效的 itertools.chain_from_iterable
方法:
flatten = itertools.chain.from_iterable
[[list(flatten(l))] for l in a]
#[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
我建议以下列表理解:
In [1]: a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
...:
In [2]: [[[a for sub in nested for a in sub]] for nested in a]
Out[2]: [[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
相当于下面的嵌套for循环:
result = []
for nested in a:
_temp = []
for sub in nested:
for a in sub:
_temp.append(a)
result.append([_temp])
不过,我更愿意这样写:
result = []
for nested in a:
_temp = []
for sub in nested:
_temp.extend(sub)
result.append([_temp])
实现两个列表串联的另一种方法如下:
a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = list(map(lambda elem: [[*elem[0], *elem[1]]],a))
print(b)
输出:
[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
我建议使用循环方法。
a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
b = []
for i in a:
new_j = []
for j in i:
new_j.extend(j)
new_i = [new_j]
b = b + [new_i]
b