📜  Python - 提取与值相同频率的元素

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

Python - 提取与值相同频率的元素

给定一个列表,提取与其值具有相同频率的所有元素。

例子:

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

在这里,获取频率的任务是使用 count() 完成的,列表理解用于迭代每个元素,比较和提取。

Python3
# Python3 code to demonstrate working of 
# Extract elements with equal frequency as value
# Using list comprehension + count()
  
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
  
# printing original list
print("The original list is : " + str(test_list))
  
# removing duplicates using set()
# count() for computing frequency
res = list(set([ele for ele in test_list if test_list.count(ele) == ele]))
  
# printing result 
print("Filtered elements : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Extract elements with equal frequency as value
# Using filter() + lambda + count()
  
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
  
# printing original list
print("The original list is : " + str(test_list))
  
# removing duplicates using set()
# count() for computing frequency
# filter used to perform filtering 
res = list(set(list(filter(lambda ele : test_list.count(ele) == ele, test_list))))
  
# printing result 
print("Filtered elements : " + str(res))


输出
The original list is : [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Filtered elements : [1, 3, 4]

方法 #2:使用filter() + lambda + count()

在这里,我们使用 filter() 和 lambda 执行过滤元素的任务,count() 再次用于获取所有元素的计数。

蟒蛇3

# Python3 code to demonstrate working of 
# Extract elements with equal frequency as value
# Using filter() + lambda + count()
  
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
  
# printing original list
print("The original list is : " + str(test_list))
  
# removing duplicates using set()
# count() for computing frequency
# filter used to perform filtering 
res = list(set(list(filter(lambda ele : test_list.count(ele) == ele, test_list))))
  
# printing result 
print("Filtered elements : " + str(res))
输出
The original list is : [4, 3, 2, 2, 3, 4, 1, 3, 2, 4, 4]
Filtered elements : [1, 3, 4]