📜  Python – 如果第 K 个元素不在 List 中,则提取记录

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

Python – 如果第 K 个元素不在 List 中,则提取记录

给定元组列表,任务是提取参数列表中不存在第 K 个索引元素的所有元组。

方法 #1:使用 set() + 循环

这是执行此任务的一种方式。在此,我们使用 set 缩短参数列表,然后有效地检查具有来自 arg 的任何元素的 Kth 索引。列出并相应地附加。

Python3
# Python3 code to demonstrate working of
# Extract records if Kth elements not in List
# Using loop
  
# initializing list
test_list = [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing arg. list
arg_list = [4, 8, 4]
  
# initializing K
K = 1
  
# Using set() to shorten arg list
temp = set(arg_list)
  
# loop to check for elements and append
res = []
for sub in test_list:
    if sub[K] not in arg_list:
        res.append(sub)
  
# printing result
print("Extracted elements : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract records if Kth elements not in List
# Using list comprehension + set()
  
# initializing list
test_list = [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing arg. list
arg_list = [4, 8, 4]
  
# initializing K
K = 1
  
# Compiling set() and conditionals into single comprehension
res = [(key, val) for key, val in test_list if val not in set(arg_list)]
  
# printing result
print("Extracted elements : " + str(res))


输出
The original list : [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)]
Extracted elements : [(5, 3), (1, 3), (0, 6)]

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

这是可以执行此任务的另一种方式。在此,我们编译了使用 set() 过滤重复项和使用列表理解中的条件编译元素的任务。

Python3

# Python3 code to demonstrate working of
# Extract records if Kth elements not in List
# Using list comprehension + set()
  
# initializing list
test_list = [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing arg. list
arg_list = [4, 8, 4]
  
# initializing K
K = 1
  
# Compiling set() and conditionals into single comprehension
res = [(key, val) for key, val in test_list if val not in set(arg_list)]
  
# printing result
print("Extracted elements : " + str(res))
输出
The original list : [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)]
Extracted elements : [(5, 3), (1, 3), (0, 6)]