Python – 包含所有 List 元素的行
给定一个矩阵,获取包含所有列表元素的所有行。
Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]], sub_list = [1, 2]
Output : [[2, 1, 8], [6, 1, 2]]
Explanation : Extracted lists have 1 and 2.
Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]], sub_list = [2, 6]
Output : [[7, 6, 3, 2], [6, 1, 2]]
Explanation : Extracted lists have 2 and 6.
方法#1:使用循环
在此,我们对 Matrix 中的每一行进行迭代,并检查每个列表元素是否存在,如果当前行作为结果返回。如果任何元素不存在,则行被标记为关闭。
Python3
# Python3 code to demonstrate working of
# Rows with all List elements
# Using loop
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing list
sub_list = [1, 2]
res = []
for row in test_list:
flag = True
# checking for all elements in list
for ele in sub_list:
if ele not in row:
flag = False
if flag:
res.append(row)
# printing result
print("Rows with list elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Rows with all List elements
# Using all() + list comprehension
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing list
sub_list = [1, 2]
# testing elements presence using all()
res = [row for row in test_list if all(ele in row for ele in sub_list)]
# printing result
print("Rows with list elements : " + str(res))
输出:
The original list is : [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]]
Rows with list elements : [[2, 1, 8], [6, 1, 2]]
方法 #2:使用all() +列表推导式
在这种情况下,使用 all() 测试存在的所有元素,列表理解被用作单行来执行遍历行的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Rows with all List elements
# Using all() + list comprehension
# initializing list
test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing list
sub_list = [1, 2]
# testing elements presence using all()
res = [row for row in test_list if all(ele in row for ele in sub_list)]
# printing result
print("Rows with list elements : " + str(res))
输出:
The original list is : [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]]
Rows with list elements : [[2, 1, 8], [6, 1, 2]]