[英]How to convert letters to numbers with python?
I have a dictionary 'g' and I want to convert all letters to numbers. 我有一本字典'g',我想将所有字母都转换为数字。
g = { "a" : ["c","e","h","m","k","i"],
"b" : ["d","f","k","m"]
}
I found this on stack overflow: 我在堆栈溢出中发现了这一点:
def alphabet_position_Headcrab(text):
nums = [str(ord(x) - 96) for x in text.lower() if x >= 'a' and x <= 'z']
return " ".join(nums)
and this one with a prefer: 和一个喜欢的人:
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])
But it works not for my dictionary but only for 1Dimensional dictionary like: 但这不适用于我的字典,而仅适用于1Dimensional字典,例如:
dic = { "a" : "g", "b" : "f"}
Thank you for your help ( perhaps is the answer obvious but I'm not an expert in coding) 谢谢您的帮助(也许答案很明显,但我不是编码专家)
如果函数适用于单个值,则应该可以将函数映射到列表值上
new_g = {k: [alphabet_position(x) for x in v] for k, v in g.items()}
This might help you 这可能对您有帮助
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.