使用另一个列表中的值屏蔽列表的Python程序
给定两个列表,任务是编写一个Python程序,将另一个列表中存在的元素标记为 1,否则标记为 0。
Input : test_list = [5, 2, 1, 9, 8, 0, 4], search_list = [1, 10, 8, 3, 9]
Output : [0, 0, 1, 1, 1, 0, 0]
Explanation : 1, 9, 8 are present in test_list at position 2, 3, 4 and are masked by 1. Rest are masked by 0.
Input : test_list = [5, 2, 1, 19, 8, 0, 4], search_list = [1, 10, 8, 3, 9]
Output : [0, 0, 1, 0, 1, 0, 0]
Explanation : 1, 8 are present in test_list at position 2, 4 and are masked by 1. Rest are masked by 0.
方法#1:使用列表理解
在此,我们遍历搜索列表和 in运算符,用于使用列表理解检查组合,并为存在分配 1,为不存在分配 0。
Python3
# Python3 code to demonstrate working of
# Boolean composition mask in list
# Using list comprehension
# initializing list
test_list = [5, 2, 1, 9, 8, 0, 4]
# printing original list
print("The original list is : " + str(test_list))
# initializing search list
search_list = [1, 10, 8, 3, 9]
# list comprehension iteration and in operator
# checking composition
res = [1 if ele in search_list else 0 for ele in test_list]
# printing result
print("The Boolean Masked list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Boolean composition mask in list
# Using set() + list comprehension
# initializing list
test_list = [5, 2, 1, 9, 8, 0, 4]
# printing original list
print("The original list is : " + str(test_list))
# initializing search list
search_list = [1, 10, 8, 3, 9]
# list comprehension iteration and in operator
# checking composition
# set() removes duplicates
res = [1 if ele in set(search_list) else 0 for ele in test_list]
# printing result
print("The Boolean Masked list : " + str(res))
输出:
The original list is : [5, 2, 1, 9, 8, 0, 4]
The Boolean Masked list : [0, 0, 1, 1, 1, 0, 0]
方法#2:使用set() +列表推导式
在这种情况下,使用 set() 从搜索列表中删除重复元素以减少搜索空间。其余所有操作与上述方法类似。
蟒蛇3
# Python3 code to demonstrate working of
# Boolean composition mask in list
# Using set() + list comprehension
# initializing list
test_list = [5, 2, 1, 9, 8, 0, 4]
# printing original list
print("The original list is : " + str(test_list))
# initializing search list
search_list = [1, 10, 8, 3, 9]
# list comprehension iteration and in operator
# checking composition
# set() removes duplicates
res = [1 if ele in set(search_list) else 0 for ele in test_list]
# printing result
print("The Boolean Masked list : " + str(res))
输出:
The original list is : [5, 2, 1, 9, 8, 0, 4]
The Boolean Masked list : [0, 0, 1, 1, 1, 0, 0]