Python – 向每個元素分配字母
當需要向整數列表的每個元素分配一個字母時,將使用“ascii_lowercase”方法和列表解析。
示例
以下是對上述內容的演示 −
import string
my_list = [11, 51, 32, 45, 21, 66, 12, 58, 90, 0]
print("The list is : " )
print(my_list)
print("The list after sorting is : " )
my_list.sort()
print(my_list)
temp_val = {}
my_counter = 0
for element in my_list:
if element in temp_val:
continue
temp_val[element] = string.ascii_lowercase[my_counter]
my_counter += 1
my_result = [temp_val.get(element) for element in my_list]
print("The resultant list is : ")
print(my_result)輸出
The list is : [11, 51, 32, 45, 21, 66, 12, 58, 90, 0] The list after sorting is : [0, 11, 12, 21, 32, 45, 51, 58, 66, 90] The resultant list is : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
解釋
所需的軟體包已匯入環境中。
定義了一個整數列表,並顯示在控制檯上。
使用“sort”方法對其進行排序,並再次顯示在控制檯上。
定義了一個空字典。
將計數器初始化為 0。
對其進行迭代,並在滿足條件時使用“continue”運算子。
否則,將使用“ascii_lowercase”方法並將其分配給字典中的某個特定索引。
使用列表解析來迭代列表並使用“get”方法。
此處的元素儲存在列表中並分配給一個變數。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP