Python|前后字符相似的字符串
有时,在编程时,我们可能会遇到需要检查每个字符串的前后字符的问题。我们可能需要提取具有相似前后字符的所有字符串的计数。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方法。在此,迭代列表的每个元素并检查每个字符串的前后字符,并增加计数器以防我们找到匹配项。
# Python3 code to demonstrate working of
# Similar front and rear elements
# Using loop
# initialize list
test_list = ['gfg', 'is', 'best', 'treat']
# printing original list
print("The original list : " + str(test_list))
# Similar front and rear elements
# Using loop
count = 0
for ele in test_list:
if ele[0] == ele[-1]:
count = count + 1
# printing result
print("Total Strings with similar front and rear elements : " + str(count))
输出 :
The original list : ['gfg', 'is', 'best', 'treat']
Total Strings with similar front and rear elements : 2
方法 #2:使用sum()
+ 生成器表达式
这是执行此任务的一种替代方案。在此,我们使用生成器表达式执行迭代任务,使用 sum() 执行求和任务。
# Python3 code to demonstrate working of
# Similar front and rear elements
# Using sum() + generator expression
# initialize list
test_list = ['gfg', 'is', 'best', 'treat']
# printing original list
print("The original list : " + str(test_list))
# Similar front and rear elements
# Using sum() + generator expression
res = sum(1 for ele in test_list if ele[0] == ele[-1])
# printing result
print("Total Strings with similar front and rear elements : " + str(res))
输出 :
The original list : ['gfg', 'is', 'best', 'treat']
Total Strings with similar front and rear elements : 2