使用多个列表的高级列表编码

时间:2019-05-23 06:57:46

标签: python

因此,我们给出了两个列表。

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

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

如何将A中的元素替换为其相应的组索引:即,将0中的1A替换为02中的A13452等。

输出:

A = [[[0, 0, 3, 3, 3, 3], [0, 0, 3, 3, 3, 3]], [[1]], [[2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3]], [[0, 0, 2, 2, 2, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3, 3]]]

4 个答案:

答案 0 :(得分:0)

即使您没有尝试,也可以尝试:

def f(l,i):
    for k in l:
        if i in k:
            return l.index(k)

output_ = [[[f(groups,n) for n in a0] for a0 in a] for a in A]

输出

[[[0, 0, 3, 3, 3, 3], [0, 0, 3, 3, 3, 3]], [[1]], [[2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3]], [[0, 0, 2, 2, 2, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3, 3]]]

答案 1 :(得分:0)

尝试一下:

def replace_items(i, inner_list, *lists):
    for l in lists:
        for item in l:
            if item in inner_list:
                index= l.index(item)
                l[index] = i

for i,inner_list in enumerate(groups):
    for lists in A:
        replace_items(i, inner_list, *lists)

print(A)

答案 2 :(得分:0)

创建一个字典,存储这些数字的索引值,然后为列表A中的这些数字添加索引

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

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

from collections import defaultdict

dic = defaultdict(int)

for i in range(len(groups)):
    for j in groups[i]:
        dic[j]=i

for i in A:
    for j in i:
        for l in range(len(j)):
            j[l] = dic[j[l]]

输出

[[[0, 0, 3, 3, 3, 3], [0, 0, 3, 3, 3, 3]],
 [[1]],
 [[2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3]],
 [[0, 0, 2, 2, 2, 3, 3, 3],
  [0, 0, 2, 2, 2, 3, 3, 3],
  [0, 0, 2, 2, 2, 3, 3, 3, 3],
  [0, 0, 2, 2, 2, 3, 3, 3, 3]]]

答案 3 :(得分:0)

如果您将群组转换为字典,则可以使用列表理解来轻松处理3级列表:

groupDict = { v:i for i,g in enumerate(groups) for v in g }
A = [ [ [ groupDict[z] for z in yz ] for yz in xyz] for xyz in A ]