将字符串拆分为 k 大小重叠字符串的Python程序
给定一个字符串,任务是编写一个Python程序,根据大小 K 从原始字符串提取重叠的连续字符串切片。
例子:
Input : test_str = ‘Geeksforgeeks’, K = 4
Output : [‘Geek’, ‘eeks’, ‘eksf’, ‘ksfo’, ‘sfor’, ‘forg’, ‘orge’, ‘rgee’, ‘geek’, ‘eeks’]
Explanation : Consecutive overlapping 4 sized strings are output.
Input : test_str = ‘Geeksforgeeks’, K = 6
Output : [‘Geeksf’, ‘eeksfo’, ‘eksfor’, ‘ksforg’, ‘sforge’, ‘forgee’, ‘orgeek’, ‘rgeeks’]
Explanation : Consecutive overlapping 6 sized strings are output.
方法一:使用islice() +生成器函数+ join()
在这种情况下,使用 islice() 提取大小为 K 的窗口,并使用 yield 以中间方式产生结果。使用 join() 连接最终结果。
Python3
# Python3 code to demonstrate working of
# Overlapping consecutive K splits
# Using islice() + generator function + join()
from itertools import islice
# generator function
def over_slice(test_str, K):
itr = iter(test_str)
res = tuple(islice(itr, K))
if len(res) == K:
yield res
for ele in itr:
res = res[1:] + (ele,)
yield res
# initializing string
test_str = 'Geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# calling generator function
res = ["".join(ele) for ele in over_slice(test_str, K)]
# printing result
print("Overlapping windows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Overlapping consecutive K splits
# Using list comprehension + slicing
# initializing string
test_str = 'Geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# extracting window using slicing
res = [test_str[idx:idx + K] for idx in range(len(test_str) - K + 1)]
# printing result
print("Overlapping windows : " + str(res))
输出:
The original string is : Geeksforgeeks
Overlapping windows : [‘Geek’, ‘eeks’, ‘eksf’, ‘ksfo’, ‘sfor’, ‘forg’, ‘orge’, ‘rgee’, ‘geek’, ‘eeks’]
方法二:使用列表推导+切片
在这个例子中,中间切片是使用切片操作以更pythonic的方式执行的。使用切片符号提取每个窗口。
蟒蛇3
# Python3 code to demonstrate working of
# Overlapping consecutive K splits
# Using list comprehension + slicing
# initializing string
test_str = 'Geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# extracting window using slicing
res = [test_str[idx:idx + K] for idx in range(len(test_str) - K + 1)]
# printing result
print("Overlapping windows : " + str(res))
输出:
The original string is : Geeksforgeeks
Overlapping windows : [‘Geek’, ‘eeks’, ‘eksf’, ‘ksfo’, ‘sfor’, ‘forg’, ‘orge’, ‘rgee’, ‘geek’, ‘eeks’]