📜  Python – 在矩阵中列出字符串频率

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

Python – 在矩阵中列出字符串频率

有时,在使用 Matrix 时,我们可能会遇到一个问题,即我们需要检查 List 中每行 Matrix 中参数字符串的频率。这是一个非常特殊的问题,可以在许多领域中发挥作用。让我们讨论可以解决此任务的某些方法。

方法 #1:使用count() + 循环
上述功能的组合可用于执行此任务。在此我们使用 count() 计算频率,并在循环内执行迭代任务。

# Python3 code to demonstrate 
# List Strings frequency in Matrix
# using count() + loop
  
# Initializing lists
test_list1 = [['Gfg', 'is', 'best'], ['Gfg', 'is', 'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']]
test_list2 = ['Gfg', 'is', 'best']
  
# printing original list1
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# List Strings frequency in Matrix
# using count() + loop
res = []
for val in test_list1:
    res.append([val.count(ele) for ele in test_list2])
  
# printing result 
print ("Frequency of strings in Matrix : " + str(res))
输出 :
The original list 1 is : [['Gfg', 'is', 'best'], ['Gfg', 'is', 'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']]
The original list 2 is : ['Gfg', 'is', 'best']
Frequency of strings in Matrix : [[1, 1, 1], [1, 1, 0], [1, 1, 0]]

方法#2:使用列表推导
这是可以执行此任务的另一种方式。这是上述方法在一个班轮中的简化版本。

# Python3 code to demonstrate 
# List Strings frequency in Matrix
# using list comprehension
  
# Initializing lists
test_list1 = [['Gfg', 'is', 'best'], ['Gfg', 'is', 'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']]
test_list2 = ['Gfg', 'is', 'best']
  
# printing original list1
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# List Strings frequency in Matrix
# using list comprehension
res = [[sub.count(ele) for ele in test_list2] for sub in test_list1]
  
# printing result 
print ("Frequency of strings in Matrix : " + str(res))
输出 :
The original list 1 is : [['Gfg', 'is', 'best'], ['Gfg', 'is', 'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']]
The original list 2 is : ['Gfg', 'is', 'best']
Frequency of strings in Matrix : [[1, 1, 1], [1, 1, 0], [1, 1, 0]]