【发布时间】:2021-02-10 17:14:53
【问题描述】:
我有一个这样的字符串:
word = 'python'
基于string.ascii_lowercase,我想创建一个如下所示的新数组:
[15, 24, 19, 7, 14, 13]
我对这个问题的解决方案是:
alphabet = {char: i for i, char in enumerate(string.ascii_lowercase)}
indices = [alphabet[char] for char in word]
print(indices)
输出:[15, 24, 19, 7, 14, 13]
但我正在寻找一种更有效的方法,而不使用循环。我怎样才能以矢量化的方式做到这一点?
【问题讨论】:
-
[ord(c) - 0x61 for c in word] -
@OlvinRoght 这不是矢量化的方式。它使用列表理解。
-
我知道,但这是使用 python 最快的方法。
-
这是典型的大小字符串吗?或者您正在使用更长的字符串?
标签: python string numpy unicode vectorization