Python – 将字符串分成相等的 K 块
给定一个 String 执行划分为 K 个相等的块。
Input : test_str = ‘geeksforgeek’, K = 4
Output : [‘gee’, ‘ksf’, ‘org’, ‘eek’]
Explanation : 12/4 = 3, length of each string extracted.
Input : test_str = ‘geeksforgeek’, K = 1
Output : [‘geeksforgeek’]
Explanation : 12/1 = 12, whole string is single chunk.
方法 #1:使用 len() + 循环
在此,我们首先执行计算 K 和字符串长度所需的每个块的长度的任务,然后,将字符串拆分为所需的索引以使用切片提取块。
Python3
# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using len() + loop
# initializing strings
test_str = 'geeksforgeeks 1'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 5
# compute chunk length
chnk_len = len(test_str) // K
res = []
for idx in range(0, len(test_str), chnk_len):
# appending sliced string
res.append(test_str[idx : idx + chnk_len])
# printing result
print("The K chunked list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using list comprehension
# initializing strings
test_str = 'geeksforgeeks 1'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 5
# compute chunk length
chnk_len = len(test_str) // K
# one-liner to perform the task
res = [test_str[idx : idx + chnk_len] for idx in range(0, len(test_str), chnk_len)]
# printing result
print("The K len chunked list : " + str(res))
输出
The original string is : geeksforgeeks 1
The K chunked list : ['gee', 'ksf', 'org', 'eek', 's 1']
方法 #2:使用列表推导
方法与上面类似,不同之处在于最后一个过程被封装为单行列表理解。
Python3
# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using list comprehension
# initializing strings
test_str = 'geeksforgeeks 1'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 5
# compute chunk length
chnk_len = len(test_str) // K
# one-liner to perform the task
res = [test_str[idx : idx + chnk_len] for idx in range(0, len(test_str), chnk_len)]
# printing result
print("The K len chunked list : " + str(res))
输出
The original string is : geeksforgeeks 1
The K len chunked list : ['gee', 'ksf', 'org', 'eek', 's 1']