📜  Python - 列表中的累积行频率

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

Python - 列表中的累积行频率

给定 Matrix,任务是编写一个Python程序来获取行中出现的总计数。

方法 #1:使用Counter() +列表理解

在这里,我们执行获取所有行的所有频率的任务,然后从行中检查所需元素的列表出现, sum() 用于获取行中提取频率的总和。

Python3
# Python3 code to demonstrate working of 
# Cumulative Row Frequencies
# Using Counter() + list comprehension
from collections import Counter 
  
# initializing list
test_list = [[10, 2, 3, 2, 3], 
             [5, 5, 4, 7, 7, 4], 
             [1, 2], [1, 1, 2, 2, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing ele_list 
ele_list = [1, 2, 7]
  
# getting each rows counter 
freqs = [Counter(ele) for ele in test_list]
  
# getting summation of present values 
res = [sum([freq[wrd] for wrd in ele_list if wrd in freq]) for freq in freqs]
  
# printing result 
print("Cumulative Frequencies : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Cumulative Row Frequencies
# Using sum() + list comprehension
  
# initializing list
test_list = [[10, 2, 3, 2, 3], 
             [5, 5, 4, 7, 7, 4],
             [1, 2], [1, 1, 2, 2, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing ele_list 
ele_list = [1, 2, 7]
  
# getting summation 
res = [sum(ele in ele_list for ele in sub) for sub in test_list]
  
# printing result 
print("Cumulative Frequencies : " + str(res))


输出:

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

在这里,我们使用 sum() 执行求和任务,列表推导用于检查检查列表中的元素并遍历行。

蟒蛇3

# Python3 code to demonstrate working of 
# Cumulative Row Frequencies
# Using sum() + list comprehension
  
# initializing list
test_list = [[10, 2, 3, 2, 3], 
             [5, 5, 4, 7, 7, 4],
             [1, 2], [1, 1, 2, 2, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing ele_list 
ele_list = [1, 2, 7]
  
# getting summation 
res = [sum(ele in ele_list for ele in sub) for sub in test_list]
  
# printing result 
print("Cumulative Frequencies : " + str(res))

输出: