如何重命名列表中的项目?

2024-09-30 20:25:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单,清单如下:

MyList = [[[[11, 12], [13, 14]], [[12, 13], [22, 23]], [[24, 34], [53, 54]], [[43, 44], [54, 55]]],
          [[[12, 13], [22, 23]], [[11, 12], [13, 14]], [[15, 25], [44, 54]], [[24, 34], [53, 54]]],
          [[[13, 14], [21, 31]], [[15, 25], [44, 54]], [[52, 53], [54, 55]]],
          [[[15, 25], [44, 54]], [[12, 13], [22, 23]], [[13, 14], [21, 31]]],
          [[[24, 34], [53, 54]], [[11, 12], [13, 14]], [[12, 13], [22, 23]]],
          [[[34, 35], [45, 55]], [[52, 53], [54, 55]]],
          [[[43, 44], [54, 55]], [[11, 12], [13, 14]]],
          [[[52, 53], [54, 55]], [[13, 14], [21, 31]], [[34, 35], [45, 55]]]]

在这个列表中,我有8项。我想这样重命名这些项目:

^{pr2}$

最后,重命名后的列表如下所示:

MyListRename = [[1, 2, 5, 7],
                [2, 1, 4, 5],
                [3, 4, 8],
                [4, 2, 3],
                [5, 1, 2],
                [6, 8],
                [7, 1],
                [8, 3, 6]]

在python中最好的方法是什么?在


Tags: 项目方法列表重命名mylistpr2mylistrename
3条回答

我将以编程的方式执行此操作,利用每个列表的第一个元素是可能元素的列表:

lookup_dict = {}
reverse_dict = {}
index = 0
for ele in MyList:
    lookup_dict[index] = ele[0]
    reverse_dict[repr(ele[0])] = index
    index += 1

注意:列表通常不能用于字典键。在本例中,我们使用^{}来获取字符串形式的表示,以用作键

然后我们可以通过以下方式压缩列表:

^{pr2}$

并通过以下方式重建原始文件:

re_list = [[lookup_dict[subele - 1] for subele in ele] for ele in result]

>>> re_list == MyList
True

如果还可以使用零索引,则可以删除+/-1以稍微降低复杂性。在

您可以使用以下函数:

def replace_list (sub_list):
    if sub_list == [[11, 12], [13, 14]]: return 1
    if sub_list == [[12, 13], [22, 23]]: return 2
    if sub_list == [[13, 14], [21, 31]]: return 3
    if sub_list == [[15, 25], [44, 54]]: return 4
    if sub_list == [[24, 34], [53, 54]]: return 5
    if sub_list == [[34, 35], [45, 55]]: return 6
    if sub_list == [[43, 44], [54, 55]]: return 7
    if sub_list == [[52, 53], [54, 55]]: return 8
    return 0 #or any default value

然后执行一个双循环for来更改MyList中的值:

^{pr2}$

甚至可以将map用于列表理解

MyList = [map(replace_list, subList) for subList in MyList]

(此解决方案绝对可以改进)

mydict = {
    ((11, 12), (13, 14)): 1,
    ((12, 13), (22, 23)): 2,
    ((13, 14), (21, 31)): 3,
    ((15, 25), (44, 54)): 4,
    ((24, 34), (53, 54)): 5,
    ((34, 35), (45, 55)): 6,
    ((43, 44), (54, 55)): 7,
    ((52, 53), (54, 55)): 8
}

newList = []
counter = 0

for outlist in myList:
    newList.append([]);

    for inList in outlist:
        obj = (tuple(inList[0]), tuple(inList[1]))
        newList[counter].append(mydict[obj])

    counter += 1

我正在使用一个字典,其中的键是表示要替换的列表的元组。请记住,列表是可变的,因此不是散列的。在

相关问题 更多 >