Python – 下标字典
有时,在Python中处理数据时,我们可能会遇到需要使用数字的下标版本而不是普通数字的问题。为此,拥有一个将数字与其下标版本映射的字典具有很好的实用性。让我们讨论可以执行此任务的某些方式。
Input : test_str = “012345”
Output : {‘0’: ‘?’, ‘1’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘4’: ‘?’, ‘5’: ‘?’}
Input : test_str = “0”
Output : {‘0’: ‘?’}
方法 #1:使用循环 + ord()
这是我们执行此任务的蛮力方式。在此,我们遍历需要下标的数字,并使用 ord() 及其二进制值构造下标值。在Python 3.7 + 中工作。
# Python3 code to demonstrate working of
# Subscript Dictionary
# Using loop + ord()
# initializing string
test_str = "0123456789"
# printing original string
print("The original string is : " + test_str)
# initializing Subscript number value
K = u'\u2080'
# Subscript Dictionary
# Using loop + ord()
res = {}
for ele in test_str:
res[ele] = K
K = chr(ord(K) + 1)
# printing result
print("The split string is : " + str(res))
The original string is : 0123456789
The split string is : {‘7’: ‘?’, ‘4’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘5’: ‘?’, ‘8’: ‘?’, ‘1’: ‘?’, ‘6’: ‘?’, ‘0’: ‘?’, ‘9’: ‘?’}
方法#2:使用字典理解
这是可以执行此任务的另一种方式。在此,我们执行与上述类似的任务,只需使用理解在单行中使用。在Python 3.7 + 中工作。
# Python3 code to demonstrate working of
# Subscript Dictionary
# Using Dictionary comprehension
# initializing string
test_str = "0123456789"
# printing original string
print("The original string is : " + test_str)
# initializing Subscript number value
K = u'\u2080'
# Subscript Dictionary
# Using Dictionary comprehension
res = {ele : chr(ord(K) + 1) for ele in test_str}
# printing result
print("The split string is : " + str(res))
The original string is : 0123456789
The split string is : {‘7’: ‘?’, ‘4’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘5’: ‘?’, ‘8’: ‘?’, ‘1’: ‘?’, ‘6’: ‘?’, ‘0’: ‘?’, ‘9’: ‘?’}