首页 > 解决方案 > What does "char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) }" do?

问题描述

What does this line of code do?

char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) }

what is the meaning of ch:i?

标签: pythonfor-loopcolon

解决方案


this is a dict comprehension as mentioned in by @han solo

the final product is a dict
it will sort your chars, attach a number in ascending order to them, and then use each character as the key to that numerical value here's an example:

chars = ['d', 'a', 'b']
sorted(chars) => ['a', 'b', 'd']
enumerate(sorted(chars)) => a generator object that unrolls into [(0, 'a'), (1, 'b'), (2, 'd')]
char_to_ix = {'a': 0, 'b': 1, 'd': 2}


推荐阅读