我有一个dict如下:
strdirList = {'W':['WEST', 'WES', 'WE'], 'E': ['EAST', 'EA'], 'N':'NORTH',
'S':'SOUTH'}
根据这个词典,如果我有一个字符串,例如:
direction1 = 'WES EXAMPLE NORTH'
direction2 = 'EXAMPLE NORTH WES'
我想得到的回报是
nameString1 = 'EXAMPLE NORTH'
direction1 = 'W'
nameString2 = 'EXAMPLE WES'
direction2 = 'N'
我目前的代码如下:
for e in range(len(directionList)):
word = list(strdirList.keys())
for i in range(len(word)):
for n in range(len(strdirList[word[i]])):
if directionList[e] == strdirList[word[i]][n]:
directionList[e] = \
directionList[e].replace(strdirList[word[i]][n], word[i])
我当前的代码是不正常的,无法正常工作,是否有更好,更优雅的方法来解决问题?非常感谢!
更新: 我想改变需要改变的第一个元素,并记录它的类,我该怎么办?
UPDATE2: 我试着自己解决,但这不仅仅是改变第一个,代码如下:
for i in range(len(directionList)):
for sdic in strdirList.keys():
if directionList[i] in strdirList[sdic]:
directionList[i] = sdic
break
for item in directionList:
if item in strdirList.keys():
directionList.remove(item)
direction = item
break
else:
direction = ''
UPDATE3: 我现在有一种解决问题的方法,如下所示,但它适用于扁平字典:
def test(strdirList, direction):
directionList = direction.split(' ')
for i in range(len(directionList)):
for sdic in strdirList.keys():
if directionList[i] in strdirList[sdic]:
directionList[i] = sdic
return directionList
directionList = test(strdirList, direction)
for item in directionList:
if item in strdirList.keys():
directionList.remove(item)
direction = item
break
else:
direction = ''
它现在对我有用,但如果有人有更优雅的方式,请在此写下你的答案!
答案 0 :(得分:2)
您可以使用re.sub
:
import re
strdirList = {'W':['WEST', 'WES', 'WE'], 'E': ['EAST', 'EA'], 'N':'NORTH',
'S':'SOUTH'}
direction = 'WES EXAMPLE NORTH'
new_direction = re.sub('\w+', lambda x:(lambda c:x.group() if not c else c[0])([a for a, b in strdirList.items() if x.group() in b]), direction)
输出:
'W EXAMPLE N'
编辑:
def get_direction(direction):
flag = False
for i in direction.split():
if any(i in c for c in strdirList.values()) and not flag:
yield [a for a, b in strdirList.items() if i in b][0]
flag = True
else:
yield i
direction = ['WES EXAMPLE NORTH', 'EXAMPLE WES NORTH', 'EXAMPLE NORTH WES']
print(list(map(lambda x:' '.join(get_direction(x)), direction)))
输出:
['W EXAMPLE NORTH', 'EXAMPLE W NORTH', 'EXAMPLE N WES']