使用列表列表从字典中访问值并返回列表列表

时间:2018-09-20 07:03:47

标签: python python-2.7 list dictionary

我有一本叫做dict的字典,它看起来像这样:

{1: [0, 1], 2: [2, 3], 3: [4], 4: [5, 6, 7, 8], 5: [9, 10], 7: [11, 12], 8: [13, 14, 15], 9: [16], 10: [17], 11: [18], 13: [19], 14: [20], 15: [21], 17: [22], 18: [23, 24], 19: [25], 21: [26, 27, 28], 22: [29], 24: [30, 31, 32], 25: [33, 34], 27: [35], 28: [36], 31: [37, 38, 39, 40, 41, 42], 32: [43, 44, 45, 46, 47], 34: [48, 49, 50, 51, 52], 35: [53, 54, 55, 56], 36: [57, 58, 59], 37: [60], 40: [61, 62], 41: [63, 64, 65, 66], 43: [67], 44: [68, 69], 45: [70, 71], 48: [72, 73, 74], 49: [75, 76], 51: [77], 52: [78, 79], 53: [80, 81], 54: [82], 55: [83], 58: [84, 85, 86], 59: [87], 61: [88, 89], 62: [90], 63: [91], 64: [92, 93], 65: [94], 68: [95], 69: [96], 71: [97], 73: [98, 99], 74: [100], 76: [101], 77: [102]}

我有一个名为keepID的列表,看起来像这样:

[[13, 24, 62, 69, 34, 31], [44, 11, 2, 55, 22, 53], [59, 40, 3, 54, 32, 71], [15, 64, 73, 5, 10], [68, 61, 9, 18, 48], [41, 58, 65, 1, 27], [37, 7, 51, 35, 25], [17, 74, 63, 8, 36]]

remainID包含一个列表列表,这些列表是字典中所有键的值。我想将maintainID中的所有键值更改为该键的字典值对。这意味着,我不希望列表中包含字典中键的多个列表,而是要一个列表,其中包含字典中值的多个列表。但是,remainID中的列表数不能更改,但是每个列表的长度可能不同。我该怎么做?

例如,考虑剩下的ID中的第一个列表: [13, 24, 62, 69, 34, 31]

此列表应变为: [19, 30, 31, 32, 90, 48, 49, 50, 51, 52, 37, 38, 39, 40, 41, 42]

2 个答案:

答案 0 :(得分:2)

您可以使用以下列表推导(假设您的字典名为d,因为您不应将其命名为dict,因为它掩盖了内置类)

remainID = [[s for i in l for s in d[i]] for l in remainID]

remainID将变为:

[[19, 30, 31, 32, 90, 96, 48, 49, 50, 51, 52, 37, 38, 39, 40, 41, 42], [68, 69, 18, 2, 3, 83, 29, 80, 81], [87, 61, 62, 4, 82, 43, 44, 45, 46, 47, 97], [21, 92, 93, 98, 99, 9, 10, 17], [95, 88, 89, 16, 23, 24, 72, 73, 74], [63, 64, 65, 66, 84, 85, 86, 94, 0, 1, 35], [60, 11, 12, 77, 53, 54, 55, 56, 33, 34], [22, 100, 91, 13, 14, 15, 57, 58, 59]]

答案 1 :(得分:0)

您可以使用list comprehension + itertools

from itertools import chain
remain_id = [list(chain.from_iterable([d.get(j) for j in i])) for i in remain_id]

结果:

Out[78]: 
[[19, 30, 31, 32, 90, 96, 48, 49, 50, 51, 52, 37, 38, 39, 40, 41, 42],
 [68, 69, 18, 2, 3, 83, 29, 80, 81],
 [87, 61, 62, 4, 82, 43, 44, 45, 46, 47, 97],
 [21, 92, 93, 98, 99, 9, 10, 17],
 [95, 88, 89, 16, 23, 24, 72, 73, 74],
 [63, 64, 65, 66, 84, 85, 86, 94, 0, 1, 35],
 [60, 11, 12, 77, 53, 54, 55, 56, 33, 34],
 [22, 100, 91, 13, 14, 15, 57, 58, 59]]