📜  Python - 过滤第二个列表中索引包含给定子字符串的字符串列表

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

Python - 过滤第二个列表中索引包含给定子字符串的字符串列表

给定两个列表,从第一个列表中提取所有元素,其在第二个列表中的对应索引包含所需的子字符串。

例子:

方法 #1:使用 zip() + loop + in运算符

在此,我们使用 zip() 组合索引,并使用 in运算符检查子字符串。循环用于迭代的任务。

Python3
# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using zip() + loop + in
# operator
 
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and",
              "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok",
              "ok", "wrong", "ok", "thats ok"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing substr
sub_str = "ok"
 
res = []
# using zip() to map by index
for ele1, ele2 in zip(test_list1, test_list2):
 
    # checking for substring
    if sub_str in ele2:
        res.append(ele1)
 
# printing result
print("The extracted list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using list comprehension + zip()
 
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and",
              "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "no", "looks ok",
              "ok", "wrong", "ok", "thats ok"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing substr
sub_str = "ok"
 
# using list comprehension to perform task
res = [ele1 for ele1, ele2 in zip(test_list1, test_list2) if sub_str in ele2]
 
# printing result
print("The extracted list : " + str(res))


输出:

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

这与上述方法类似。这里唯一的区别是列表推导被用作解决问题的速记。

Python3

# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using list comprehension + zip()
 
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and",
              "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "no", "looks ok",
              "ok", "wrong", "ok", "thats ok"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing substr
sub_str = "ok"
 
# using list comprehension to perform task
res = [ele1 for ele1, ele2 in zip(test_list1, test_list2) if sub_str in ele2]
 
# printing result
print("The extracted list : " + str(res))

输出: