简体   繁体   中英

Convert each element in a list to a corresponding (predefined) dictionary value

The coding challenge from Codewars

I want to map each corresponding value in an array to my new defined dictionary such that

'NORTH': 1, 'SOUTH': -1, 'EAST': 1, 'WEST': -1

Here, each key corresponds to a an individual element in a given list and the values in the dict is what I want the new elements of said list to equal to.

I then intend on taking the sum of the new list to find the "reduced direction"

Any help would be appreciated. Thank you!

You can use map .

>>> src = ['NORTH','SOUTH','EAST','EAST']
>>> adict = {'NORTH': 1, 'SOUTH': -1, 'EAST': 1, 'WEST': -1}
>>> sum(map(adict.__getitem__,src))
2
>>>

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