以奇怪的方式组合 2 个列表
Combining 2 lists in strange way
假设我有这两个列表列表。
[[1.0, 100.0], [2.0, 100.0], [3.0, 100.0], [4.0, 100.0], [5.0, 100.0]]
[[1.0, 20.0], [2.0, 20.0], [3.0, 0.0]]
注意不同的尺寸,我想将它们组合起来创建下面的列表
[[1.0, 100.0, 20.0], [2.0, 100.0, 20.0], [3.0, 100.0, 0.0], [4.0, 100.0], [5.0, 100.0]]
它们可以是任意数量的列表,它们可以是任意长度。
如果您想要唯一值并组合任意长度的列表:
from itertools import chain, izip_longest,ifilter
obj = object()
from collections import OrderedDict
print([list(ifilter(lambda x: x is not obj, OrderedDict.fromkeys(chain.from_iterable(tup))))
for tup in (tup for tup in izip_longest(l1,l2,fillvalue=[obj]))])
输出:
[[1.0, 100.0, 20.0], [2.0, 100.0, 20.0], [3.0, 100.0, 0.0], [4.0, 100.0], [5.0, 100.0]]
如果顺序无关紧要,您可以在 tup 上调用 set
而不是 OrderedDict。
假设我有这两个列表列表。
[[1.0, 100.0], [2.0, 100.0], [3.0, 100.0], [4.0, 100.0], [5.0, 100.0]]
[[1.0, 20.0], [2.0, 20.0], [3.0, 0.0]]
注意不同的尺寸,我想将它们组合起来创建下面的列表
[[1.0, 100.0, 20.0], [2.0, 100.0, 20.0], [3.0, 100.0, 0.0], [4.0, 100.0], [5.0, 100.0]]
它们可以是任意数量的列表,它们可以是任意长度。
如果您想要唯一值并组合任意长度的列表:
from itertools import chain, izip_longest,ifilter
obj = object()
from collections import OrderedDict
print([list(ifilter(lambda x: x is not obj, OrderedDict.fromkeys(chain.from_iterable(tup))))
for tup in (tup for tup in izip_longest(l1,l2,fillvalue=[obj]))])
输出:
[[1.0, 100.0, 20.0], [2.0, 100.0, 20.0], [3.0, 100.0, 0.0], [4.0, 100.0], [5.0, 100.0]]
如果顺序无关紧要,您可以在 tup 上调用 set
而不是 OrderedDict。