Python|混合列表中按字典顺序最小的字符串
有时,我们也会遇到一个问题,给定一个混合列表,并要求找到列表中出现的字典最小的字符串。这个问题可以找到它的应用程序日日编程。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用min() + isinstance()
+ 列表理解
可以使用上述功能的组合来执行此任务。在此, min()
函数执行查找最小字符串的任务, isinstance()
用于检查字符串。
# Python3 code to demonstrate working of
# Lexicographically smallest string in mixed list
# Using min() + isinstance() + list comprehension
# initializing list
test_list = [1, 2, 4, "GFG", 5, "IS", 7, "BEST"]
# printing original list
print("The original list is : " + str(test_list))
# Lexicographically smallest string in mixed list
# Using min() + isinstance() + list comprehension
res = min(sub for sub in test_list if isinstance(sub, str))
# printing result
print("The Lexicographically smallest string is : " + str(res))
输出 :
The original list is : [1, 2, 4, 'GFG', 5, 'IS', 7, 'BEST']
The Lexicographically smallest string is : BEST
方法 #2:使用min()
+ lambda + filter()
上述功能的组合也可用于执行此特定任务。在此我们使用filter()
和 lambda 和min
函数执行列表理解的任务,用于执行查找最小字符串的常规任务。
# Python3 code to demonstrate working of
# Lexicographically smallest string in mixed list
# Using min() + lambda + filter()
# initializing list
test_list = [1, 2, 4, "GFG", 5, "IS", 7, "BEST"]
# printing original list
print("The original list is : " + str(test_list))
# Lexicographically smallest string in mixed list
# Using min() + lambda + filter()
res = min(filter(lambda s:isinstance(s, str), test_list))
# printing result
print("The Lexicographically smallest string is : " + str(res))
输出 :
The original list is : [1, 2, 4, 'GFG', 5, 'IS', 7, 'BEST']
The Lexicographically smallest string is : BEST