📜  Python – 将大于 K 的元素存储为字典

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

Python – 将大于 K 的元素存储为字典

有时,在使用Python列表时,我们可能会遇到需要提取大于 K 的元素的问题。但有时,我们不需要存储重复性,因此不需要在字典中存储键值对。跟踪字典中出现的数字位置。

方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们通过检查大于 K 的元素以字典的形式存储元素。

# Python3 code to demonstrate 
# Storing Elements Greater than K as Dictionary
# using loop
  
# Initializing list
test_list = [12, 44, 56, 34, 67, 98, 34]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K 
K = 50
  
# Storing Elements Greater than K as Dictionary
# using loop
res = dict()
count = 1
for ele in test_list:
    if ele > K:
        res[count] = ele
        count = count + 1
          
# printing result 
print ("The dictionary after storing elements : " + str(res))
输出 :
The original list is : [12, 44, 56, 34, 67, 98, 34]
The dictionary after storing elements : {1: 56, 2: 67, 3: 98}

方法#2:使用字典理解
这是可以执行此任务的另一种方式。在此,我们只是使用字典理解和 enumerate() 进行索引,在一个短结构中执行类似的任务。

# Python3 code to demonstrate 
# Storing Elements Greater than K as Dictionary
# using dictionary comprehension
  
# Initializing list
test_list = [12, 44, 56, 34, 67, 98, 34]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K 
K = 50
  
# Storing Elements Greater than K as Dictionary
# using dictionary comprehension
res = {idx: ele for idx, ele in enumerate(test_list) if ele >= K}
          
# printing result 
print ("The dictionary after storing elements : " + str(res))
输出 :
The original list is : [12, 44, 56, 34, 67, 98, 34]
The dictionary after storing elements : {2: 56, 4: 67, 5: 98}