Python – 挤压 K 的连续值
有时,在使用Python列表时,我们可能会遇到需要删除特定元素的重复连续值的问题。这类问题可以在许多领域都有应用,例如竞争性编程和 Web 开发。让我们讨论可以执行此任务的某些方式。
Input : test_list = [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5], K = 3
Output : [4, 5, 5, 4, 3, 5, 5, 5, 6, 5]
Input : test_list = [1, 1, 1, 1], K = 1
Output : [1]
方法#1:使用 zip() + yield
上述功能的组合提供了解决这个问题的方法之一。在此,我们使用压缩当前和下一个元素列表来执行检查连续重复的任务,并且使用产量来呈现条件的元素基础。
Python3
# Python3 code to demonstrate working of
# Squash consecutive values of K
# Using zip() + yield
# helper function
def hlper_fnc(test_list, K):
for sub1, sub2 in zip(test_list, test_list[1:]):
if sub1 == sub2 == K:
continue
else:
yield sub1
yield sub2
# initializing list
test_list = [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# Squash consecutive values of K
# Using zip() + yield
res = list(hlper_fnc(test_list, K))
# printing result
print("List after filtration : " + str(res))
Python3
# Python3 code to demonstrate working of
# Squash consecutive values of K
# Using yield + groupby()
import itertools
# helper function
def hlper_fnc(test_list, K):
for key, val in itertools.groupby(test_list):
if key == K:
yield key
else:
yield from val
# initializing list
test_list = [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# Squash consecutive values of K
# Using yield + groupby()
res = list(hlper_fnc(test_list, K))
# printing result
print("List after filtration : " + str(res))
输出 :
The original list is : [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5]
List after filteration : [4, 5, 4, 3, 3, 5, 6, 5]
方法 #2:使用 yield + groupby()
上述功能的组合可以用来解决这个问题。在此,我们使用 groupby() 执行分组任务,以检查连续性,并使用 yield 来返回有效元素。
Python3
# Python3 code to demonstrate working of
# Squash consecutive values of K
# Using yield + groupby()
import itertools
# helper function
def hlper_fnc(test_list, K):
for key, val in itertools.groupby(test_list):
if key == K:
yield key
else:
yield from val
# initializing list
test_list = [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# Squash consecutive values of K
# Using yield + groupby()
res = list(hlper_fnc(test_list, K))
# printing result
print("List after filtration : " + str(res))
输出 :
The original list is : [4, 5, 5, 4, 3, 3, 5, 5, 5, 6, 5]
List after filteration : [4, 5, 4, 3, 3, 5, 6, 5]