📜  Python - 按字母顺序提取具有连续字母的字符串

📅  最后修改于: 2022-05-13 01:55:21.286000             🧑  作者: Mango

Python - 按字母顺序提取具有连续字母的字符串

给定一个字符串列表,提取包含按字母顺序出现的任何连续字符的列表。

方法#1:使用 ord() + 循环

在这里,我们检查每个字符串是否包含并且字符是其前一个字符的字母后继,ASCII 转换是使用 ord() 完成的。

Python3
# Python3 code to demonstrate working of 
# Extract Strings with successive Alphabets
# Using ord() + loop
  
# initializing string list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
res = []
for sub in test_list:
      
    # iterating for string 
    for idx in range(len(sub) - 1):
          
        # checking for alphabetic consecution
        if ord(sub[idx]) == ord(sub[idx + 1]) - 1:
            res.append(sub)
            break
      
# printing result 
print("Strings with alphabetic consecution : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract Strings with successive Alphabets
# Using any() + filter() + lambda
  
# initializing string list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# filtering using filter, and checking for any substring using any()
res = list(filter(lambda sub: any(ord(sub[idx]) == ord(
    sub[idx + 1]) - 1 for idx in range(len(sub) - 1)), test_list))
  
# printing result
print("Strings with alphabetic consecution : " + str(res))


输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Strings with alphabetic consecution : ['gfg', 'best']

方法#2:使用 any() + filter() + lambda

在这里,我们使用 any() 检查任何连续性,并使用 filter() 和 lambda函数完成过滤任务。

蟒蛇3

# Python3 code to demonstrate working of
# Extract Strings with successive Alphabets
# Using any() + filter() + lambda
  
# initializing string list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# filtering using filter, and checking for any substring using any()
res = list(filter(lambda sub: any(ord(sub[idx]) == ord(
    sub[idx + 1]) - 1 for idx in range(len(sub) - 1)), test_list))
  
# printing result
print("Strings with alphabetic consecution : " + str(res))
输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Strings with alphabetic consecution : ['gfg', 'best']