
本教程详细讲解如何从python嵌套列表中提取每个子列表中最短的字符串。文章首先分析了不恰当的最小值初始化导致空列表输出的常见错误,随后提供了使用`sys.maxsize`进行正确初始化并通过`map`函数处理嵌套列表的解决方案。此外,还介绍了利用python内置`min()`函数配合`key`参数实现更简洁高效的代码,并讨论了处理多个最短字符串及空子列表的策略。
在Python编程中,我们经常需要处理包含多层数据结构的列表,例如一个由多个子列表组成的列表。一个常见的需求是从每个子列表中找出满足特定条件的元素,例如最短的字符串。本文将通过一个具体案例,深入探讨如何高效且正确地实现这一目标,并分析常见的编程陷阱。
假设我们有一个包含电影或电视剧名称的嵌套列表,my_movies:
my_movies = [
['How I Met Your Mother', 'Friends', 'Silicon Valley'],
['Family Guy', 'South Park', 'Rick and Morty'],
['Breaking Bad', 'GOT', 'The Wire', 'The Last of Us']
]我们的目标是从my_movies中的每个子列表里,找出长度最短的字符串,并将这些最短字符串收集到一个新的列表中。例如,对于第一个子列表['How I Met Your Mother', 'Friends', 'Silicon Valley'],最短的字符串是'Friends'(长度为7)。
用户最初尝试使用以下代码来实现:
立即学习“Python免费学习笔记(深入)”;
def min_length(movies):
all_small_movies = []
minlen = 2 # 初始化的最小值
for movie in movies:
if len(movie) < minlen:
minlen = len(movie)
all_small_movies = [movie]
return all_small_movies
small_new_list = list(map(min_length, my_movies))
print(small_new_list)这段代码在运行时会返回 [[], [], []],即一个包含空列表的列表。其主要问题出在两个方面:
不恰当的 minlen 初始化值: 函数 min_length 被设计用来查找给定列表中长度最短的字符串。然而,minlen 被初始化为 2。当函数处理第一个子列表 ['How I Met Your Mother', 'Friends', 'Silicon Valley'] 时,其中的字符串长度分别为 20、7、14。所有这些长度都大于或等于 minlen (2),因此 if len(movie) < minlen 条件从未满足。结果,all_small_movies 始终保持为空列表 []。
map() 函数的应用:list(map(min_length, my_movies)) 的作用是将 my_movies 中的每个子列表(例如 ['How I Met Your Mother', 'Friends', 'Silicon Valley'])作为参数,分别传递给 min_length 函数进行处理。由于 min_length 每次都返回 [],最终 map 收集到的结果就是 [[], [], []]。
要解决上述问题,我们需要对 min_length 函数进行改进,确保 minlen 的初始值足够大,以便能正确比较所有字符串的长度。最常用的方法是使用 sys.maxsize(系统所能表示的最大整数),或者直接将第一个元素的长度作为初始值。
sys.maxsize 是一个非常大的整数,可以确保任何字符串的长度都小于它,从而使第一次比较就能正确地更新 minlen。
import sys
my_movies = [
['How I Met Your Mother', 'Friends', 'Silicon Valley'],
['Family Guy', 'South Park', 'Rick and Morty'],
['Breaking Bad', 'GOT', 'The Wire', 'The Last of Us']
]
def find_shortest_string(list_of_strings):
"""
从一个字符串列表中找出长度最短的字符串。
如果存在多个相同最短长度的字符串,则返回第一个遇到的。
"""
shortest_string = None
min_length_found = sys.maxsize # 初始化为系统最大整数
for s in list_of_strings:
if len(s) < min_length_found:
min_length_found = len(s)
shortest_string = s # 更新为当前最短字符串
return shortest_string
# 使用 map() 将函数应用到每个子列表
shortest_movies_per_sublist = list(map(find_shortest_string, my_movies))
print(shortest_movies_per_sublist)输出结果:
['Friends', 'Family Guy', 'GOT']
代码解析:
另一种初始化方式是使用列表的第一个元素的长度。但这种方法需要额外处理列表为空的情况。
def find_shortest_string_v2(list_of_strings):
if not list_of_strings: # 处理空列表情况
return None # 或者返回空字符串 '',视具体需求而定
shortest_string = list_of_strings[0] # 假设第一个是目前最短的
min_length_found = len(list_of_strings[0])
for s in list_of_strings[1:]: # 从第二个元素开始遍历
if len(s) < min_length_found:
min_length_found = len(s)
shortest_string = s
return shortest_string
shortest_movies_per_sublist_v2 = list(map(find_shortest_string_v2, my_movies))
print(shortest_movies_per_sublist_v2)这种方法同样能得到正确的结果,但需要额外的条件判断来避免空列表时的索引错误。
Python 内置的 min() 函数提供了一个 key 参数,可以指定一个函数来计算列表中每个元素的比较值。这使得查找最短(或最长)字符串变得非常简洁。
my_movies = [
['How I Met Your Mother', 'Friends', 'Silicon Valley'],
['Family Guy', 'South Park', 'Rick and Morty'],
['Breaking Bad', 'GOT', 'The Wire', 'The Last of Us']
]
def get_shortest_string_pythonic(list_of_strings):
"""
使用 min() 函数和 key 参数从字符串列表中找出长度最短的字符串。
"""
if not list_of_strings:
return None # 处理空列表情况
return min(list_of_strings, key=len)
# 使用列表推导式或 map()
shortest_movies_pythonic = [get_shortest_string_pythonic(sublist) for sublist in my_movies]
# 或者
# shortest_movies_pythonic = list(map(get_shortest_string_pythonic, my_movies))
print(shortest_movies_pythonic)输出结果:
['Friends', 'Family Guy', 'GOT']
代码解析:
处理多个相同最短长度的字符串: 上述所有解决方案在遇到多个长度相同的最短字符串时,都会返回第一个遇到的那个。如果需要返回所有最短字符串,需要修改逻辑:
def find_all_shortest_strings(list_of_strings):
if not list_of_strings:
return []
min_length_found = sys.maxsize
all_shortest = []
for s in list_of_strings:
if len(s) < min_length_found:
min_length_found = len(s)
all_shortest = [s]以上就是Python教程:从嵌套列表中高效提取最短字符串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号