简体   繁体   English

有没有办法遍历列表并根据字典替换值?

[英]Is there a way to iterate through a list and replace values based on a dictionary?

I have created a list of routes with the following layout:我创建了具有以下布局的路线列表:

routes = [[14,133,101,40,55,149,41,165,45,182,220,104,110,100,117,126,205,64,194,118,203],
 [7, 145, 111, 7, 180, 168, 136, 33, 70, 222, 190, 83, 233, 103],
 [185, 124, 185, 82, 195],
 [185, 91, 60, 8, 6],
 [220, 43, 179, 214],
 [7, 226, 187, 25, 152, 94, 46, 13, 19, 79, 125],
 [104, 72, 89, 51, 2, 172],
 [7, 147, 130, 160, 54, 116, 77, 156, 142, 78, 200, 122],
 [7, 175, 138, 49, 96, 148, 88, 123, 207, 97, 112, 169],
 [104, 201, 167, 53, 42, 15],
 [7, 95, 34, 137, 36, 20, 56, 164, 129, 5, 16],
 [3, 44, 71, 48, 102, 131, 139, 30, 221, 22, 57, 23, 66, 204, 99],
 [220, 114, 150, 217],
 [104, 170, 87, 174, 140, 134],
 [7, 193, 86, 202, 59, 143, 108, 21, 155, 198],
 [104, 162, 230, 166, 173],
 [185, 177, 127, 208, 158],
 [185, 227, 178, 176],
 [220, 224, 98],
 [185, 232, 37],
 [185, 225]]

These numbers correspond to a dictionary index, like the one below:这些数字对应于一个字典索引,如下所示:

{1: 4,
 2: 38,
 3: 71,
 4: 90,
 5: 94,
 6: 101,
 7: 142,
 8: 163,
 9: 164,
 10: 196,
 ...
 234: 8360,
 235: 8507,
 236: 8545}

I want to iterate through the route list replacing every number with the corresponding value from the dictionary, eg convert the 7 in routes into 142. I have tried to do this using the code below:我想遍历路由列表,用字典中的相应值替换每个数字,例如将路由中的 7 转换为 142。我尝试使用以下代码执行此操作:

([d.get(x,"No_key") for x in routes])

but this gives the following error:但这会产生以下错误:

TypeError: unhashable type: 'list'

It seems to work when I instead do this:当我这样做时,它似乎有效:

([d.get(x,"No_key") for x in routes[0]])

But I would like a way to carry this out for a route list of indeterminate length instead of having to go through the list manually row by row但我想要一种方法来为不确定长度的路线列表执行此操作,而不必逐行手动通过列表 go

Is there another way to iterate through and replace these values?是否有另一种方法来迭代和替换这些值?

You have a list of lists, not a single flat list, so you have to use two nested list comprehensions:您有一个列表列表,而不是单个平面列表,因此您必须使用两个嵌套列表推导:

routes = [
    [
        d.get(index, "No_key")
        for index in route
    ]
    for route in routes
]

Use 2 list comprehensions:使用 2 个列表推导:

routes = [[2, 3, 1], [6, 5, 4]]
dct = {1: 4,
       2: 38,
       3: 71,
       4: 90,
       5: 94,
       6: 101,
}

routes = [[dct[k] for k in lst] for lst in routes]
print(routes)
# [[38, 71, 4], [101, 94, 90]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM