我希望实现的是以特定模式排列列表中的项目。说,我有以下字典:
>>>dict_a = {
'north' : 'N',
'south' : 'S',
'east' : 'E',
'west' : 'W',
'north east' : 'NE',
'north west' : 'NW'
}
现在检查字符串是否包含上述字典中的任何项目:
>>>string_a = 'North East Asia'
>>>list_a = []
>>>for item in dict_a:
if item in string_a.lower():
list_a.append(item)
它给我的结果如下,这是有道理的
>>>['north', 'north east', 'east']
但我想得到的是['north east']
并忽略north
和east
。我如何实现这一目标?
答案 0 :(得分:5)
>>> dict_a = {
'north' : 'N',
'south' : 'S',
'east' : 'E',
'west' : 'W',
'north east' : 'NE',
'north west' : 'NW'
}
>>> import difflib
>>> string_a = 'North East Asia'
>>> dict_a[difflib.get_close_matches(string_a, dict_a.keys())[0]]
'NE'
答案 1 :(得分:3)
您可以使用OrderedDict
(Python 2.7+中的新增功能),它以一致的顺序存储键/值对。要获得单个结果,只需在第一次匹配后中断循环。
import collections
# create the mapping with the desired order of matches
dict_a = collections.OrderedDict([
('north east', 'NE'),
('north west', 'NW'),
('north', 'N'),
('south', 'S'),
('east', 'E'),
('west', 'W'),
])
string_a = 'North East Asia'
list_a = []
for item in dict_a:
if item in string_a.lower():
list_a.append(item)
break # found something
答案 2 :(得分:2)
>>> max(['north', 'north east', 'east'], key=len)
'north east'