将字符串转换为 K 大小的数字行的Python程序
给定字符串字母,将其转换为 K 大小的数字行,其中包含作为字符位置值的数字。
Input : test_str = ‘geeksforgeek’, K = 4
Output : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10]]
Explanation : g is at 6th position in alphabet hence g→ 6 and the string is split after every fourth character
Input : test_str = ‘geeksforgeek’, K = 3
Output : [[6, 4, 4], [10, 18, 5], [14, 17, 6], [4, 4, 10]]
Explanation : g is at 6th position in alphabet hence g→ 6 and the string is split after every third character
方法 1:使用循环 + index()
在此,我们使用循环对每个字符进行迭代,并在有序字符列表上使用 index() 获取字符在字母表中的所需位置。
Python3
# initializing string
test_str = 'geeksforgeekscse'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
alphabs = "abcdefghijklmnopqrstuvwxyz"
res = []
temp = []
for ele in test_str:
# finding numerical position using index()
temp.append(alphabs.index(ele))
# regroup on K
if len(temp) == K:
res.append(temp)
temp = []
# appending remaining characters
if temp != []:
res.append(temp)
# printing result
print("Grouped and Converted String : " + str(res))
Python3
from math import ceil
# initializing string
test_str = 'geeksforgeekscse'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# filling the rear to K size rows
temp = test_str.ljust(ceil(len(test_str) / K) * K)
# convert to numerical characters
temp = [0 if char == ' ' else (ord(char) - 97) for char in temp]
# slice and render to matrix
res = [temp[idx: idx + K] for idx in range(0, len(temp), K)]
# printing result
print("Grouped and Converted String : " + str(res))
输出:
The original string is : geeksforgeekscse
Grouped and Converted String : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10], [18, 2, 18, 4]]
方法#2:使用 ljust() + ord() + 列表理解
在此,我们使用 ljust() 执行需要具有相等长度行的填充任务,然后使用 ord() 获取数字字母位置,列表理解与切片有助于将列表转换为 K 分块矩阵。
蟒蛇3
from math import ceil
# initializing string
test_str = 'geeksforgeekscse'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# filling the rear to K size rows
temp = test_str.ljust(ceil(len(test_str) / K) * K)
# convert to numerical characters
temp = [0 if char == ' ' else (ord(char) - 97) for char in temp]
# slice and render to matrix
res = [temp[idx: idx + K] for idx in range(0, len(temp), K)]
# printing result
print("Grouped and Converted String : " + str(res))
输出:
The original string is : geeksforgeekscse
Grouped and Converted String : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10], [18, 2, 18, 4]]