Python - 矩阵中带有 K字符串的行
给定一个矩阵,提取具有特定字符串出现的行号。
Input : test_list = [[“GFG”, “best”, “geeks”], [“geeks”, “rock”], [“GFG”, “for”, “CS”], [“Keep”, “learning”]], K = “GFG”
Output : [0, 2]
Explanation : 0th index and 2nd index have “GFG” in them as element.
Input : test_list = [[“GFG”, “best”, “geeks”], [“geeks”, “rock”, “GFG”], [“GFG”, “for”, “CS”], [“Keep”, “learning”]], K = “GFG”
Output : [0, 1, 2]
Explanation : 0th index, 1st index and 2nd index have “GFG” in them as element.
方法#1:使用循环
在此,我们迭代 Matrix 中的每个元素并获取与 K 字符串匹配的所有行的索引。
Python3
# Python3 code to demonstrate working of
# Rows with K string in Matrix
# Using loop
# initializing list
test_list = [["GFG", "best", "geeks"], ["geeks", "rock"],
["GFG", "for", "CS"], ["Keep", "learning"]]
# printing original list
print("The original list is : ", test_list)
# initializing K
K = "GFG"
res = []
# enumerate() used for getting both index and ele
for idx, ele in enumerate(test_list):
# checking for K String
if K in ele:
res.append(idx)
# printing result
print("Rows with K : " + str(res))
Python3
# Python3 code to demonstrate working of
# Rows with K string in Matrix
# Using list comprehension
# initializing list
test_list = [["GFG", "best", "geeks"], ["geeks", "rock"],
["GFG", "for", "CS"], ["Keep", "learning"]]
# printing original list
print("The original list is : ", test_list)
# initializing K
K = "GFG"
# shorthand to get result
res = [idx for idx, ele in enumerate(test_list) if K in ele]
# printing result
print("Rows with K : " + str(res))
输出:
The original list is : [[‘GFG’, ‘best’, ‘geeks’], [‘geeks’, ‘rock’], [‘GFG’, ‘for’, ‘CS’], [‘Keep’, ‘learning’]]
Rows with K : [0, 2]
方法#2:使用列表理解
这与上述方法类似,不同之处在于它是解决问题的速记。
蟒蛇3
# Python3 code to demonstrate working of
# Rows with K string in Matrix
# Using list comprehension
# initializing list
test_list = [["GFG", "best", "geeks"], ["geeks", "rock"],
["GFG", "for", "CS"], ["Keep", "learning"]]
# printing original list
print("The original list is : ", test_list)
# initializing K
K = "GFG"
# shorthand to get result
res = [idx for idx, ele in enumerate(test_list) if K in ele]
# printing result
print("Rows with K : " + str(res))
输出:
The original list is : [[‘GFG’, ‘best’, ‘geeks’], [‘geeks’, ‘rock’], [‘GFG’, ‘for’, ‘CS’], [‘Keep’, ‘learning’]]
Rows with K : [0, 2]