Python – 在第 K 个字符上对字符串进行分组
有时,在使用Python字符串时,我们可能会遇到需要根据Python字符串的第 K 个字符对其进行分组的问题。这类问题可能出现在日常编程中。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的一种方式。在此,我们使用蛮力方法执行分组任务。我们迭代每个字符串,并在使用条件语句进行条件检查后对字典进行分组。
# Python3 code to demonstrate working of
# Groups Strings on Kth character
# Using loop
from collections import defaultdict
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# Groups Strings on Kth character
# Using loop
res = defaultdict(list)
for word in test_list:
res[word[K - 1]].append(word)
# printing result
print("The strings grouping : " + str(dict(res)))
输出 :
The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’]
The strings grouping : {‘f’: [‘gfg’], ‘s’: [‘is’], ‘e’: [‘best’, ‘geeks’], ‘o’: [‘for’]}
方法 #2:使用map()
+ 循环
这是解决此问题的另一种方法。在此变体中,使用 map() 添加了对有效字符的附加测试。
# Python3 code to demonstrate working of
# Groups Strings on Kth character
# Using loop + map()
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# Groups Strings on Kth character
# Using loop + map()
res = dict()
for char in map(chr, range(97, 123)):
words = [idx for idx in test_list if idx[K - 1] == char]
if words:
res[char] = words
# printing result
print("The strings grouping : " + str(res))
输出 :
The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’]
The strings grouping : {‘f’: [‘gfg’], ‘s’: [‘is’], ‘e’: [‘best’, ‘geeks’], ‘o’: [‘for’]}