如何通过其元素将嵌套列表拆分为两个嵌套列表?

How to split a nested list into two nested list by its element?

我在拆分嵌套列表时遇到问题。有一个我输入的例子:

l = [[[35, 58, 'A'], [0, 18, 'B'], [76, 101, 'B'], [103, 130, 'A'], [134, 158, 'A']], [[2, 51, 'A'], [55, 115, 'B'], [125, 150, 'B']]]

我想通过第三个元素将其拆分为两个单独的嵌套列表:

l_b = [[[0,18], [76,101]], [[55, 115], [125,150]]]
l_a = [[[35,58], [103, 130], [134,158]], [[2,51]]]

我尝试使用循环搜索:

for i in l:
    for ii in i:
        if ii[2] == 'A':
            l_a.append(ii)

但我只是得到一个简单的列表,所以我丢失了索引。 提前致谢 ;)

取消嵌套列表,对其进行迭代并将每个元素的一部分插入到键下的字典中。

l = [[[35, 58, 'A'], [0, 18, 'B'], [76, 101, 'B'], [103, 130, 'A'], 
     [134, 158, 'A']], [[2, 51, 'A'], [55, 115, 'B'], [125, 150, 'B']]]

flat = [k for x in l for k in x]
print(flat)

from collections import defaultdict

# this will automatically create the key with a list if needed
# no need to prepopulate it if you got "C"s and "D"s later on as well
grp = defaultdict(list)

for elem in flat:
    # use 3rd element as key, use slice of first two as data
    # will crash on less then 3 elements but your data is ok
    grp[elem[2]].append(elem[:2])

print(*grp.items(), sep="\n")

输出:

#flat
[[35, 58, 'A'], [0, 18, 'B'], [76, 101, 'B'], [103, 130, 'A'], 
 [134, 158, 'A'], [2, 51, 'A'], [55, 115, 'B'], [125, 150, 'B']]

# grouped
('A', [[35, 58], [103, 130], [134, 158], [2, 51]])
('B', [[0, 18], [76, 101], [55, 115], [125, 150]])

如果需要,您可以 re-nest 列表 - 只是觉得其中没有多大意义:

l_a = [grp["A"]]

您可以在代码后简单地使用 l_a = [l_a] 来重新嵌套它。

如果出于某种原因需要保留嵌套结构:

l = [[[35, 58, 'A'], [0, 18, 'B'], [76, 101, 'B'], [103, 130, 'A'], [134, 158, 'A']], [[2, 51, 'A'], [55, 115, 'B'], [125, 150, 'B']]]
l_a = []

for i in l:
    tmp_list = []
    for ii in i:
        if ii[2] == 'A':
            tmp_list.append(ii[:2])
    l_a.append(tmp_list)

首先创建空列表l_a,然后l_b,在if 语句之后,您需要切片ii[:2] 以仅包含数字。 最后,包括 else 语句以附加 B 存在的值。

l = [[[35, 58, 'A'], [0, 18, 'B'], [76, 101, 'B'], [103, 130, 'A'], [134, 158, 'A']], [[2, 51, 'A'], [55, 115, 'B'], [125, 150, 'B']]]
l_a_outer =[]
for i in l:
    l_a = []
    for ii in i:
        if ii[2] == 'A':
            l_a.append(ii)
    l_a_outer.append(l_a)
print(l_a_outer)

示例输出

[[[35, 58, 'A'], [103, 130, 'A'], [134, 158, 'A']], [[2, 51, 'A']]

当您专门针对“A”和“B”时,您可以只为这两个列表准备一个字典,然后通过字典键填充这些列表:

l = [[[35, 58, 'A'], [0, 18, 'B'], [76, 101, 'B'], [103, 130, 'A'], [134, 158, 'A']], [[2, 51, 'A'], [55, 115, 'B'], [125, 150, 'B']]]

l_a = []
l_b = []
res = { "A": l_a, "B": l_b }
for chunk in l:
    l_a.append([])
    l_b.append([])
    for *values, letter in chunk:
        res[letter][-1].append(values)

print(l_a)  # [[[35, 58], [103, 130], [134, 158]], [[2, 51]]]
print(l_b)  # [[[0, 18], [76, 101]], [[55, 115], [125, 150]]]