[英]Unpack a single element from a list of lists python
I have zipped some data into as following:我已将一些数据压缩成以下内容:
list1 = [1,33,3]
list2 = [2,44,23]
list3 = [[3,4,5,6],[3,4,5,3],[4,5,3,1]]
list4 = [4,34,4]
data = [list(x) for x in zip(list1, list2, list3, list4)]
However, list3 is a list of lists.但是,list3 是列表的列表。 So the output ended up being
所以 output 最终成为
[[1,2,[3,4,5,6],4],
[33,44,[3,4,5,3],34],
[3,23,[4,5,3,1],4]]
I would like to unpack the list inside the lists like the following:我想解压缩列表中的列表,如下所示:
[[1,2,3,4,5,6,4],
[33,44,3,4,5,3,34],
[3,23,4,5,3,1,4]]
What is the best way to do that in python?在 python 中做到这一点的最佳方法是什么?
Cheers干杯
First, we have to know what we should do.首先,我们必须知道我们应该做什么。
The problem is only because list3
is a nested list
and this is causing us problems.问题只是因为
list3
是一个嵌套list
,这给我们带来了问题。 To come up with a solution we have to think on how to turn list3 from a nested to a normal list
.要提出解决方案,我们必须考虑如何将 list3 从嵌套列表转变为普通
list
。
To point out:
指出:
- the shape of
list3
is well-defined and it's always the same.list3
的形状定义明确,并且始终相同。- list3 is nested hence we have to think methods to flatten the list.
list3 是嵌套的,因此我们必须考虑扁平化列表的方法。
Finally I come up with 2 possible methods最后我想出了两种可能的方法
list3
list3
I would suggest to flatten list3
, using itertools.chain.from_iterable
.我建议使用
itertools.chain.from_iterable
展平list3
。
chain.from_iterable(iterable)
Alternate constructor for chain().
chain() 的替代构造函数。 Gets chained inputs from a single iterable argument that is evaluated lazily.
从延迟评估的单个可迭代参数获取链接输入。
this can flatten a list of lists.这可以展平列表列表。
Here is a possible implementation:这是一个可能的实现:
import itertools
list1 = [1,33,3]
list2 = [2,44,23]
list3 = [[3,4,5,6],[3,4,5,3],[4,5,3,1]]
list4 = [4,34,4]
flat_list3 = itertools.chain.from_iterable(list3)
data = [list(x) for x in zip(list1, list2, list3, list4)]
>>> [[1,2,3,4,5,6,4],
[33,44,3,4,5,3,34],
[3,23,4,5,3,1,4]]
NOTE : This possibility is slower and applicable for nested lists that aren't of a particular shape.注意:这种可能性较慢,适用于不是特定形状的嵌套列表。
You could use the deepflatten
with the map
builtin function.您可以将
deepflatten
与map
内置 function 一起使用。
Here is the equivalent to the defined function and arguments.这里等效于定义的 function 和 arguments。
deepflatten(iterable, depth=None, types=None, ignore=None)
From the docs:从文档:
Flatten an iterable with given depth.
展平具有给定深度的可迭代对象。
>>> from iteration_utilities import deepflatten
>>> data = [[1, 2, [3, 4, 5, 6], 4], [33, 44, [3, 4, 5, 3], 34], [3, 23, [4, 5, 3, 1], 4]]
>>> list(map(lambda x:list(deepflatten(x)),data))
[[1, 2, 3, 4, 5, 6, 4], [33, 44, 3, 4, 5, 3, 34], [3, 23, 4, 5, 3, 1, 4]]
If only two level-deep, you can try with first principles:如果只有两个层次,你可以尝试第一原则:
out = [
[e for x in grp for e in (x if isinstance(x, list) else [x])]
for grp in zip(list1, list2, list3, list4)
]
>>> out
[[1, 2, 3, 4, 5, 6, 4], [33, 44, 3, 4, 5, 3, 34], [3, 23, 4, 5, 3, 1, 4]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.