📜  Python - 提取排序字符串

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

Python - 提取排序字符串

给定一个字符串列表,提取所有排序的字符串。

方法 #1:使用列表理解 + sorted()

在这里,我们使用sorted()执行对字符串进行排序和比较的任务,使用列表理解来遍历字符串。

Python3
# Python3 code to demonstrate working of
# Extract sorted strings
# Using list comprehension + sorted()
  
# initializing list
test_list = ["hint", "geeks", "fins", "Gfg"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# sorted(), converts to sorted version and compares with
# original string
res = [sub for sub in test_list if ''.join(sorted(sub)) == sub]
  
# printing result
print("Sorted Strings : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Extract sorted strings
# Using filter() + lambda + sorted() + join()
  
# initializing list
test_list = ["hint", "geeks", "fins", "Gfg"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# sorted(), converts to sorted version and compares with 
# original string
res = list(filter(lambda sub : ''.join(sorted(sub)) == sub, test_list))
  
# printing result 
print("Sorted Strings : " + str(res))


输出
The original list is : ['hint', 'geeks', 'fins', 'Gfg']
Sorted Strings : ['hint', 'fins', 'Gfg']

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

在这里,我们使用filter() + lambda进行过滤,并使用join()将最终排序的字符列表结果转换为字符串进行比较。

蟒蛇3

# Python3 code to demonstrate working of 
# Extract sorted strings
# Using filter() + lambda + sorted() + join()
  
# initializing list
test_list = ["hint", "geeks", "fins", "Gfg"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# sorted(), converts to sorted version and compares with 
# original string
res = list(filter(lambda sub : ''.join(sorted(sub)) == sub, test_list))
  
# printing result 
print("Sorted Strings : " + str(res))
输出
The original list is : ['hint', 'geeks', 'fins', 'Gfg']
Sorted Strings : ['hint', 'fins', 'Gfg']