简体   繁体   中英

arrange list items in a specific pattern

What I am looking to achieve is to arrange items in a list in a specific pattern. Say, I have the following dictionary:

>>>dict_a = {
       'north' : 'N',
       'south' : 'S',
       'east' : 'E',
       'west' : 'W',
       'north east' : 'NE',
       'north west' : 'NW'
   }

Now to check if a string contains any items from the above dictionary i do :

>>>string_a = 'North East Asia'
>>>list_a = []
>>>for item in dict_a:
       if item in string_a.lower():
           list_a.append(item)

and it gives me the results as follows, which makes sense

>>>['north', 'north east', 'east']

but what I want to get is ['north east'] and ignore north and east . How do i acheive this ?

Try difflib.closest_match

>>> 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'

You can use an OrderedDict (new in Python 2.7+) which stores the key/value pairs in a consistent order. To get a single result, simply break the loop after the first match.

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
>>> max(['north', 'north east', 'east'], key=len)
'north east'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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