python - "char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) }"是做什么的?

标签 python dictionary

这行代码做了什么?

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

ch:i 是什么意思?

最佳答案

这是@han solo 中提到的字典理解

最终产品是字典
它会对你的 chars 进行排序,按升序为它们附加一个数字,然后使用每个字符作为该数值的键 这是一个例子:

chars = ['d', 'a', 'b']
排序(字符) => ['a', 'b', 'd']
enumerate(sorted(chars)) => 展开到 [(0, 'a'), (1, 'b'), (2, 'd')] 中的生成器对象
char_to_ix = {'a': 0, 'b': 1, 'd': 2}

关于python - "char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) }"是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54750750/

相关文章:

vb.net - 字典访问 : composite key vs concatenated string index

python - 当发送带有 UTF-8 字符的附件时,Flask 会引发 UnicodeEncodeError (latin-1)

python - 解构和重建python字典

ios - 无法访问 NSDictionary

javascript - D3 添加缩放和平移到 map

loops - 在 Logramm 中循环字典

python - 这段代码中出现 "object has no attribute"的原因是什么?

python - 你如何卸载 python 包/库

python - 在重复检测算法中合并独立分数以形成总分

python - 如果此列表中的值不在该嵌套字典的键之一内,如何删除该值?