📌  相关文章
📜  根据唯一字符数对字符串列表进行排序的Python程序

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

根据唯一字符数对字符串列表进行排序的Python程序

给定一个字符串列表。任务是按唯一字符数对字符串列表进行排序。

例子:

方法 #1:使用 sort() + len() + set()

在这里,我们使用 sort() 执行排序任务,并且使用 len 和 sort 函数获取字符串中唯一字符的长度。

Python3
# Python3 code to demonstrate working of 
# Sort Strings by Unique characters
# Using sort() + len() + set()
  
# helper function
def hlper_fnc(ele):
      
    # getting Unique elements count 
    return len(list(set(ele)))
  
# initializing list
test_list = ['gfg', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# perform sort
test_list.sort(key = hlper_fnc)
      
# printing result 
print("Sorted List : " + str(test_list))


Python3
# Python3 code to demonstrate working of 
# Sort Strings by Unique characters
# Using sorted() + len() + set() + lambda
  
# initializing list
test_list = ['gfg', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# perform sort
res = sorted(test_list, key = lambda sub : len(list(set(sub))))
      
# printing result 
print("Sorted List : " + str(res))


输出
The original list is : ['gfg', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'best', 'geeks']

方法 #2:使用sorted() + len() + set() + lambda

与上述方法类似,不同之处在于不是就地排序,而且还使用 lambda函数来执行任务。

蟒蛇3

# Python3 code to demonstrate working of 
# Sort Strings by Unique characters
# Using sorted() + len() + set() + lambda
  
# initializing list
test_list = ['gfg', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# perform sort
res = sorted(test_list, key = lambda sub : len(list(set(sub))))
      
# printing result 
print("Sorted List : " + str(res))
输出
The original list is : ['gfg', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'best', 'geeks']