我有一个字典'g',我想将所有字母都转换为数字。
g = { "a" : ["c","e","h","m","k","i"],
"b" : ["d","f","k","m"]
}
我在堆栈溢出时发现了这一点:
def alphabet_position_Headcrab(text):
nums = [str(ord(x) - 96) for x in text.lower() if x >= 'a' and x <= 'z']
return " ".join(nums)
和一个喜欢的人:
def alphabet_position_wvxvw(text):
result, i = [32, 32, 32] * len(text), 0
for c in bytes(text.lower(), 'ascii'):
if 97 <= c < 106:
result[i] = c - 48
i += 2
elif 106 <= c < 116:
result[i] = 49
result[i + 1] = c - 58
i += 3
elif 116 <= c <= 122:
result[i] = 50
result[i + 1] = c - 68
i += 3
return bytes(result[:i-1])
但是它不适用于我的字典,而仅适用于一维字典,例如:
dic = { "a" : "g", "b" : "f"}
感谢您的帮助(也许答案很明显,但我不是编码专家)
答案 0 :(得分:0)
如果函数适用于单个值,则应该可以在列表值上映射函数
new_g = {k: [alphabet_position(x) for x in v] for k, v in g.items()}
答案 1 :(得分:0)
这可能对您有帮助
for key, value in g.items():
nums = [str(ord(x) - 96) for x in value if x.lower() >= 'a' and x.lower() <= 'z']
g[key] = nums