📜  Python - 矩阵中带有 K字符串的行

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

Python - 矩阵中带有 K字符串的行

给定一个矩阵,提取具有特定字符串出现的行号。

方法#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))


输出:

方法#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))

输出: