如何减少Python中类似的if语句?

3

我正在处理一个项目,需要将数字值转换为字母字符,目前有以下代码:

if finposb == "2":
    finposb = "a"
if finposb == "3":
    finposb = "b"
if finposb == "4":
    finposb = "c"
if finposb == "5":
    finposb = "d"
if finposb == "6":
    finposb = "e"
if finposb == "7":
    finposb = "f"
if finposb == "8":
    finposb = "g"
if finposb == "9":
    finposb = "h"

我想知道是否有一种方法可以将这个代码行缩短,谢谢!


3
为此制作一本词典。 - Gahan
9个回答

7
letters='abcdefghijklmnopqrstuvwxyz'
finposb=letters[int(finposb)-2]

这应该可以运行,不需要字典。如果你想要更简短:

finposb='abcdefghijklmnopqrstuvwxyz'[int(finposb)-2]

3
可以对字符串进行索引,不需要使用列表。 - chepner

7
您不需要任何中间数据结构;使用 finposb 的 ASCII 值(在 Python 3 中是 Unicode 码点)即可。
# ord("a") - ord("2") == 47
finposb = chr(ord(finposb) + 47)

如果您没有像这样一个好的隐式规则,您可以使用string.maketrans创建一个翻译表,并使用string.translate将该表应用于您的输入。

>>> tbl = string.maketrans("23456789", "abcdefgh")
>>> string.translate("2", tbl)
'a'

translate函数在翻译表中找不到第一个参数时,作为一个恒等函数:

>>> string.translate("z", tbl)
'z'

3

使用字典:

DIGIT2LETTER = {
    "2": "a", "3": "b", "4": "c", "5": "d", "6": "e", "7": "f", "8": "g", "9": "h"
}
finposb = DIGIT2LETTER[finposb]

3
在这种情况下,字典可能是你要找的东西。
finposb = {
    "2": "a",
    ...
    "9": "h"
}

>>> print(finposb["2"])
a

一个字典的优点是你可以将多个键映射到同一个值,例如如果你想让 "2"2 都映射到 "a",你可以这样写:
finposb["2"] = "a"  # string
finposb[2] = "a"    # numeric

此外,有两种合理的方法从键(如“2”到“a”)中获取您的值。
finposb[key]  # raise KeyError if key is not in the dictionary
finposb.get(key, None)  # default to None if the key is missing

第一种方法很方便,因为它会报告一个有用的错误,并确保你的字典中没有这个键,而第二种方法有很多其他方便之处,比如能够在键不存在时返回自身。

finposb.get(key, key)  # returns key if key does not map to a value

传统上,这种类型的表格被用来查找字符集,例如ASCII表,许多字符可以以一种紧凑的方式存储(不然你怎么向计算机表示字母呢?),并在稍后由程序进行解释。

更现代化的形式是称为unicode,它可以用来描述非常多不同于“正常”的拉丁字母之外的字符。


2
>>> pool = {"2": "a", "3": "b", "4": "c", "5": "d", "6": "e", "7": "f", "8": "g", "9": "h"}
>>> finposb = '2'  # get any digit here
>>> if str(finposb) in pool.keys():
    finposb = pool[str(finposb)]


>>> finposb
'a'

如果您在字典中使用数字作为字符串,则整个代码片段中都要将其表示为字符串。

您不需要一直调用 str;所有的值已经是字符串了。 - chepner
我使用了str()方法来检查数字是否为整数格式,以防止程序执行中断。 - Gahan

2

您可以滥用内置的chr(),并获得以下结果:

finposb = chr(int(finposb)+95)

不需要硬编码列表。


2
import string
finposb = string.ascii_lowercase[int(finposb)-2]

移除了硬编码的字符 - pramod
1
string.ascii_lowercase[...] 是合法的;无需先构建列表。 - chepner

1
使用这个。
import string
finposb.translate(string.maketrans("".join([str(i) for i in range(2,10)]), "abcdefgh"))

或更简单
import string
finposb.translate(string.maketrans("23456789", "abcdefgh"))

0
我会像这样使用字典推导式:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
finposd = {letter:alphabet.index(letter) + 2 for letter in alphabet}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接