📜  Python – 具有最多独特字符的字符串

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

Python – 具有最多独特字符的字符串

有时,在使用Python字符串时,我们可能会遇到一个问题,即我们希望提取具有最多唯一字符的特定列表。这类问题可以应用在竞争性编程和 Web 开发领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用 max() + 字典理解
上述功能的组合可用于执行此任务。在此,我们首先使用字典收集每个字符的频率,然后使用 max() 计算具有最多唯一字符的字符串。

# Python3 code to demonstrate 
# String with most unique characters
# using max() + dictionary comprehension
  
# Initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeksc']
  
# printing original list
print("The original list is : " + str(test_list))
  
# String with most unique characters
# using max() + dictionary comprehension
temp =  {idx : len(set(idx)) for idx in test_list}
res = max(temp, key = temp.get)
  
# printing result 
print ("The string with most unique characters is : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best', 'for', 'geeksc']
The string with most unique characters is : geeksc

方法 #2:使用max() + key + lambda
上述方法的组合可用于执行此任务。在此,我们以与上述类似的方式执行此任务,不同之处在于我们使用 lambda函数将逻辑扩展到每个字符串以进行计算,而不是使用理解。

# Python3 code to demonstrate 
# String with most unique characters
# using max() + key + lambda
  
# Initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeksc']
  
# printing original list
print("The original list is : " + str(test_list))
  
# String with most unique characters
# using max() + key + lambda
res = max(test_list, key = lambda sub: len(set(sub)), default = None)
  
# printing result 
print ("The string with most unique characters is : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best', 'for', 'geeksc']
The string with most unique characters is : geeksc