Python程序使用后缀按K长度对字符串进行分组
给定字符串列表,任务是编写一个Python程序,将它们分组为 K 长度的后缀。
Input : test_list = [“food”, “peak”, “geek”, “good”, “weak”, “sneek”], K = 3
Output : {‘ood’: [‘food’, ‘good’], ‘eak’: [‘peak’, ‘weak’], ‘eek’: [‘geek’, ‘sneek’]}
Explanation : words ending with ood are food and good, hence grouped.
Input : test_list = [“peak”, “geek”, “good”, “weak”], K = 3
Output : {‘ood’: [‘good’], ‘eak’: [‘peak’, ‘weak’], ‘eek’: [‘geek’]}
Explanation : word ending with ood is good, hence grouped.
方法 1:使用 try/except + 循环
在此,我们提取最后 K 个字符并形成一个字符串,并将其附加到与其对应的现有键的列表中,如果没有找到,则通过 catch 流并创建一个带有第一个单词初始化列表的新键。
Python3
# Python3 code to demonstrate working of
# Group Strings by K length Suffix
# Using try/except + loop
# initializing list
test_list = ["food", "peak", "geek",
"good", "weak", "sneek"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
res = {}
for ele in test_list:
# extracting suffix
suff = ele[-K : ]
# appending if key found, else creating new one
try:
res[suff].append(ele)
except:
res[suff] = [ele]
# printing result
print("The grouped suffix Strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Group Strings by K length Suffix
# Using defaultdict() + loop
from collections import defaultdict
# initializing list
test_list = ["food", "peak", "geek",
"good", "weak", "sneek"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
res = defaultdict(list)
for ele in test_list:
# extracting suffix
suff = ele[-K : ]
# appending into matched suffix key
res[suff].append(ele)
# printing result
print("The grouped suffix Strings : " + str(dict(res)))
输出:
The original list is : [‘food’, ‘peak’, ‘geek’, ‘good’, ‘weak’, ‘sneek’]
The grouped suffix Strings : {‘ood’: [‘food’, ‘good’], ‘eak’: [‘peak’, ‘weak’], ‘eek’: [‘geek’, ‘sneek’]}
方法 2:使用 defaultdict() + 循环。
此方法避免了使用 try/except 块的需要,因为默认列表初始化由 defaultdict() 处理。
蟒蛇3
# Python3 code to demonstrate working of
# Group Strings by K length Suffix
# Using defaultdict() + loop
from collections import defaultdict
# initializing list
test_list = ["food", "peak", "geek",
"good", "weak", "sneek"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
res = defaultdict(list)
for ele in test_list:
# extracting suffix
suff = ele[-K : ]
# appending into matched suffix key
res[suff].append(ele)
# printing result
print("The grouped suffix Strings : " + str(dict(res)))
输出:
The original list is : [‘food’, ‘peak’, ‘geek’, ‘good’, ‘weak’, ‘sneek’]
The grouped suffix Strings : {‘ood’: [‘food’, ‘good’], ‘eak’: [‘peak’, ‘weak’], ‘eek’: [‘geek’, ‘sneek’]}