简体   繁体   English

将列表中的每个元素转换为相应的(预定义的)字典值

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

The coding challenge from Codewars Codewars 的编码挑战

I want to map each corresponding value in an array to my new defined dictionary such that我想将数组中的每个对应值 map 到我新定义的字典中,这样

'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.在这里,每个键对应于给定list中的一个单独元素,并且dict中的值是我希望所述list的新元素等于的值。

I then intend on taking the sum of the new list to find the "reduced direction"然后我打算对新list的总和找到“减少的方向”

Any help would be appreciated.任何帮助,将不胜感激。 Thank you!谢谢!

You can use map .您可以使用map

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将每个列表元素转换为嵌套字典键 - Convert each list element into a nested dictionary key 如何将每个字典值插入到对应键之后的列表中? - How to Insert Each Dictionary Value into a List After the Corresponding Key? Pandas,字典列表,其中值是一个列表。 将字典键转换为列名。 将值列表中的每个元素转换为一行 - Pandas, list of dictionaries where values are a list. Convert dictionary keys into column names. Convert each element in value list to a row 为集合中的每个元素打印字典的对应键 - print corresponding key of dictionary for each element in a set 通过获取字典值来修改列表列表中每个元组的第一个元素 - Modifying the first element of each tuple in a list of list by getting a dictionary value 来自单个列表值的相应字典关键字? - Corresponding dictionary key from single list value? 检查列表是否是字典中的键并返回相应的值 - checking if a list is a key in a dictionary and returning corresponding value 熊猫为字典值中列表的每个元素创建一列? - Pandas create a column for each element of a list in a dictionary value? 将列表的每个元素与其在另一个元素中的对应索引进行比较 - Comparing each element of a list to their corresponding index in another 如何从元素(列表)中找到匹配值(字典),并打印相应的匹配项? - How to find matching value(dictionary) from an element(list), and printing corresponding match?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM