我的口述如下:
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])
我目前的代码是不正常的,不工作,有没有更好的和优雅的方式来解决这个问题?非常感谢!你知道吗
更新: 我只想更改第一个需要更改的元素,并记录它的类,我该怎么办?你知道吗
更新2: 我试着自己解决,但不只是修改第一个,代码如下:
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 = ''
更新3: 我目前有一个解决问题的方法,如下所示,但它只适用于平底词典:
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 = ''
现在对我来说确实有效,但是如果有人有更好的优雅方式,请把你的答案写在这里!你知道吗
您可以使用
re.sub
:输出:
编辑:
输出:
相关问题 更多 >
编程相关推荐