📜  Python – 为每个元素分配字母

📅  最后修改于: 2022-05-13 01:55:23.154000             🧑  作者: Mango

Python – 为每个元素分配字母

给定一个元素列表,将相似的字母分配给相同的元素。

方法 #1:使用 ascii_lowercase() + 循环 + 列表理解

在此,我们使用 lowercase() 提取所有小写字母,并创建将相同元素映射到相似字符的字典,然后使用列表推导将其展平为适当的索引。

Python3
# Python3 code to demonstrate working of
# Assign Alphabet to each element
# Using ascii_lowercase() + loop + list comprehension
import string
 
# initializing list
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
 
# printing list
print("The original list : " + str(test_list))
 
temp = {}
cntr = 0
for ele in test_list:
    if ele in temp:
        continue
     
    # assigning same Alphabet to same element
    temp[ele] = string.ascii_lowercase[cntr]
    cntr += 1
     
# flattening
res = [temp.get(ele) for ele in test_list]
 
# printing results
print("The mapped List : " + str(res))


Python3
# Python3 code to demonstrate working of
# Assign Alphabet to each element
# Using defaultdict() + ascii_lowercase() + iter()
from collections import defaultdict
import string
 
# initializing list
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
 
# printing list
print("The original list : " + str(test_list))
 
# assigning lowercases as iterator
temp = iter(string.ascii_lowercase)
 
# lambda functions fits to similar elements
res = defaultdict(lambda: next(temp))
 
# flatten in list
res = [res[key] for key in test_list]
 
# printing results
print("The mapped List : " + str(list(res)))


输出
The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']

方法 #2:使用 defaultdict() + ascii_lowercase() + iter()

在此我们使用 defaultdict() 为相似的元素赋值, ascii_lowercase() 用于获取所有小写所有小写字母。

Python3

# Python3 code to demonstrate working of
# Assign Alphabet to each element
# Using defaultdict() + ascii_lowercase() + iter()
from collections import defaultdict
import string
 
# initializing list
test_list = [4, 5, 2, 4, 2, 6, 5, 2, 5]
 
# printing list
print("The original list : " + str(test_list))
 
# assigning lowercases as iterator
temp = iter(string.ascii_lowercase)
 
# lambda functions fits to similar elements
res = defaultdict(lambda: next(temp))
 
# flatten in list
res = [res[key] for key in test_list]
 
# printing results
print("The mapped List : " + str(list(res)))
输出
The original list : [4, 5, 2, 4, 2, 6, 5, 2, 5]
The mapped List : ['a', 'b', 'c', 'a', 'c', 'd', 'b', 'c', 'b']