Python – 如果第 K 个元素不在 List 中,则提取记录
给定元组列表,任务是提取参数列表中不存在第 K 个索引元素的所有元组。
Input : test_list = [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)], arg_list = [6, 8, 8], K = 1
Output : [(5, 3), (7, 4), (1, 3)]
Explanation : All the elements which have either 6 or 8 at 1st index are removed.
Input : test_list = [(5, 3), (7, 4)], arg_list = [3, 3, 3, 3], K = 1
Output : [(7, 4)]
Explanation : (5, 3) is removed as it has 3 at 1st index.
方法 #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)]