📜  Python程序分配每个列表元素值等于其大小顺序

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

Python程序分配每个列表元素值等于其大小顺序

给定一个列表,任务是编写一个Python程序来为每个元素分配等于其数量级的值。

方法一:使用set() + zip() + dict() + list comprehension

在此,我们执行使用 zip() 将集合转换列表的排序索引映射到值的任务,然后转换为映射到值的值字典。然后列表理解用于列表中的排序。

Python3
# Python3 code to demonstrate working of
# Relative Size Ordering 
# Using set() + zip() + sorted() + dict() + list comprehension
  
# initializing list
test_list = [8, 3, 5, 8, 1, 5, 4]
               
# printing original list
print("The original list is : " + str(test_list))
  
# assigning order to each value
ord_dict = dict(zip(list(set(test_list)),
                    range(len(set(test_list)))))
  
# mapping element with ordered value
res = [ord_dict[ele] for ele in test_list]
  
# printing result
print("Relative size ordered list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Relative Size Ordering 
# Using sorted() + set() + index() + list comprehension
  
# initializing list
test_list = [8, 3, 5, 8, 1, 5, 4]
               
# printing original list
print("The original list is : " + str(test_list))
  
# getting order
ord_dict = list(set(test_list))
  
# mapping index
res = [ord_dict.index(ele) for ele in test_list]
  
# printing result
print("Relative size ordered list : " + str(res))


输出:

The original list is : [8, 3, 5, 8, 1, 5, 4]
Relative size ordered list : [4, 1, 3, 4, 0, 3, 2]

方法 2:使用sorted() + set() + index() +列表理解

在此,我们执行转换任务以设置然后排序,使用 index() 和列表理解完成索引到顺序的映射。

蟒蛇3

# Python3 code to demonstrate working of
# Relative Size Ordering 
# Using sorted() + set() + index() + list comprehension
  
# initializing list
test_list = [8, 3, 5, 8, 1, 5, 4]
               
# printing original list
print("The original list is : " + str(test_list))
  
# getting order
ord_dict = list(set(test_list))
  
# mapping index
res = [ord_dict.index(ele) for ele in test_list]
  
# printing result
print("Relative size ordered list : " + str(res))

输出:

The original list is : [8, 3, 5, 8, 1, 5, 4]
Relative size ordered list : [4, 1, 3, 4, 0, 3, 2]