简体   繁体   English

为 Python 中的字母分配数值

[英]Assign value numbers for alphabet in Python

I have alphabets that I want to assign as follows:我有要分配的字母表,如下所示:

lowercase items az have value of 1-26 uppercase items AZ have value of 27-52小写字母 az 的值为 1-26 大写字母 AZ 的值为 27-52

What is the shortest way to implement this实现这个的最短方法是什么

[a,B,h,R] Expected Output: [1,28,8,44] [a,B,h,R] 预期 Output:[1,28,8,44]

How can we go about doing this in Python go Python 怎么办

Thank you谢谢

The python string module is perfect for this. python字符串模块非常适合这个。

from string import ascii_letters
print([ascii_letters.index(letter) + 1 for letter in ["a", "B", "h", "R"]])

I think I recognize an Advent of Code question: I developed the alphabet to score mapping as follows:我想我认出了一个 Advent of Code 问题:我开发了字母表来得分映射,如下所示:

import string
from collections import OrderedDict
lower_priorities = OrderedDict(zip(string.ascii_lowercase, range(1,27)))
upper_priorities = OrderedDict(zip(string.ascii_uppercase, range(27,53)))

You can then call the dictionary by the letter value you are interested in after checking whether is is uppercase or lowercase and then sorting it to the correct dictionary.然后,您可以在检查是大写还是小写然后将其排序到正确的字典后,通过您感兴趣的字母值调用字典。 Otherwise, combine the two dictionaries and just query the combined dictionary, ie lower_priorities["a"] would return 1 .否则,合并两个字典并仅查询合并后的字典,即lower_priorities["a"]将返回1 Loop through your array and obtain your outputs.循环遍历您的数组并获得您的输出。 Can't guarantee it's the shortest, but I can say it works!不能保证它是最短的,但我可以说它有效!

This is a way that you can implement what you want:这是您可以实现所需内容的一种方式:

print([ord(item) - 38 if ord(item) < 97 else ord(item) - 96 for item in ['a','B','h','R']])

converting each item into an int value and finding which positioning they are in (Capitalized letters come before lowercase)将每个项目转换为一个 int 值并找到它们所在的位置(大写字母在小写字母之前)

https://appdividend.com/2022/06/15/how-to-convert-python-char-to-int/ https://appdividend.com/2022/06/15/how-to-convert-python-char-to-int/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM