如何删除Python字典列表中的值中的特殊字符?

1 人不认可

我想把所有的'/api/1/employees/'和/api/1/seats/从python词典中删除。最简单的方法是什么。我的字典目前看起来是这样的 -

dict1 = {5051: ['/api/1/employees/4027', '5051', '/api/1/seats/19014'], 5052: ['/api/1/employees/4048', '5052', '/api/1/seats/19013'], 5053: ['/api/1/employees/4117', '5053', '/api/1/seats/19012'], 5054: ['/api/1/employees/15027', '5054', '/api/1/seats/9765']}

我期待着以下的决定

dict1 = {5051: ['4027', '5051', '19014'], 5052: ['4048', '5052', '19013'], 5053: ['4117', '5053', '19012'], 5054: ['15027', '5054', '9765']}
    
2 个评论
是否有可能在最后有一个"/"?
请提供足够的代码,以便其他人能够更好地理解或重现这个问题。
python
dictionary
Ashu
Ashu
发布于 2021-09-23
4 个回答
user2390182
user2390182
发布于 2021-09-23
已采纳
0 人赞同

Use str.rsplit :

dict1 = {k: [s.rsplit("/", 1)[-1] for s in v] for k, v in dict1.items()}
    
balderman
balderman
发布于 2021-09-23
0 人赞同

下面的方法可行。我们的想法是尝试将条目转换为 int ,如果我们失败了--分割条目并返回最后一个元素

data = {5051: ['/api/1/employees/4027', '5051', '/api/1/seats/19014'],
         5052: ['/api/1/employees/4048', '5052', '/api/1/seats/19013'],
         5053: ['/api/1/employees/4117', '5053', '/api/1/seats/19012'],
         5054: ['/api/1/employees/15027', '5054', '/api/1/seats/9765']}
def get_int(value):
        x = int(value)
        return value
    except ValueError:
        return value.split('/')[-1]
data = {k: [get_int(vv) for vv in v] for k,v in data.items()}
print(data)

output

{5051: ['4027', '5051', '19014'], 5052: ['4048', '5052', '19013'], 5053: ['4117', '5053', '19012'], 5054: ['15027', '5054', '9765']}
    
Danish Bansal
Danish Bansal
发布于 2021-09-23
0 人赞同

使用下面的重码词

import re
regex = r"[0-9][0-9]+"
dict1 = {5051: ['/api/1/employees/4027', '5051', '/api/1/seats/19014'],
         5052: ['/api/1/employees/4048', '5052', '/api/1/seats/19013'],
         5053: ['/api/1/employees/4117', '5053', '/api/1/seats/19012'],
         5054: ['/api/1/employees/15027', '5054', '/api/1/seats/9765']}
for i in dict1:
    dict1[i] = [re.findall(regex, j)[0] if len(re.findall(regex, j)) >= 1 else j for j in dict1[i]]
print(dict1)