Python - 按第一个元素值的频率限制元组
给定一个元组列表,任务是编写一个Python程序来将元组值的第一个元素的频率限制为最多 K。
例子:
Input : test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)], K = 2
Output : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4), (4, 7)]
Explanation : 2 occurs 2 times in result list, (2, 5), the 3rd occurrence is omitted.
Input : test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)], K = 3
Output : [(2, 3), (3, 3), (1, 4), (4, 7)]
Explanation : 2, 3, 1, 4 restricted to their 1st occurrence.
方法一:使用循环+ keys() +条件语句
在这里,我们执行记忆元组第 1 个位置的每个元素的计数的任务,如果它的出现次数增加 K,则省略。
Python3
# Python3 code to demonstrate working of
# Restrict Tuples by frequency of first element's value
# Using loop + keys() + conditional statements
# initializing list
test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5),
(3, 4), (1, 4), (3, 4), (4, 7)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
res = []
mem = dict()
for sub in test_list:
# check in memory
if sub[0] not in mem.keys():
mem[sub[0]] = 1
else:
mem[sub[0]] += 1
# add if less than K frequency
if mem[sub[0]] <= K:
res.append(sub)
# printing result
print("Filtered tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Restrict Tuples by frequency of first element's value
# Using defaultdict() + filter() + lambda
from collections import defaultdict
# initializing list
test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5),
(3, 4), (1, 4), (3, 4), (4, 7)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
mem = defaultdict(list)
# filtering result using filter() and lambda function
res = list(filter(lambda sub: mem[sub[0]].append(
sub[0]) or len(mem[sub[0]]) <= K, test_list))
# printing result
print("Filtered tuples : " + str(res))
输出:
The original list is : [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)]
Filtered tuples : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4), (4, 7)]
方法 #2:使用defaultdict() + filter() + lambda
在这里,我们使用 defaultdict() 和 filter() 执行记忆任务,并且 lambda 函数用于在满足条件时检查和添加结果的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Restrict Tuples by frequency of first element's value
# Using defaultdict() + filter() + lambda
from collections import defaultdict
# initializing list
test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5),
(3, 4), (1, 4), (3, 4), (4, 7)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
mem = defaultdict(list)
# filtering result using filter() and lambda function
res = list(filter(lambda sub: mem[sub[0]].append(
sub[0]) or len(mem[sub[0]]) <= K, test_list))
# printing result
print("Filtered tuples : " + str(res))
输出:
The original list is : [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)]
Filtered tuples : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4), (4, 7)]