Python函数返回空列表[[],[],[]]问题求助
问题分析
你的代码存在两个核心问题:
- 函数逻辑错误:你初始化
minlen=2,但所有电影名的长度都远大于2,导致len(movies)<minlen的条件永远不成立,all_small_movies始终是空列表。同时函数的循环逻辑完全偏离了“找子列表中最短字符串”的需求。 - map用法不匹配:
map(min_length, my_movies)会把my_movies里的每个子列表单独传给min_length函数,但你的函数是按处理整个二维列表写的,两者逻辑不匹配。
修正方案
方法1:提取所有最短字符串(含多个长度相同的情况)
调整函数逻辑,让它专门处理单个子列表,筛选出所有长度最短的字符串:
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_strings(sublist): if not sublist: return [] # 先获取子列表中字符串的最小长度 min_len = min(len(s) for s in sublist) # 筛选所有长度等于最小长度的字符串 return [s for s in sublist if len(s) == min_len] small_new_list = [get_shortest_strings(sublist) for sublist in my_movies] print(small_new_list)
运行结果:[['Friends'], ['Family Guy', 'South Park', 'Rick and Morty'], ['GOT']]
方法2:提取任意一个最短字符串(简洁写法)
如果只需要每个子列表里第一个遇到的最短字符串,直接用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']] small_new_list = [min(sublist, key=len) for sublist in my_movies] print(small_new_list)
运行结果:['Friends', 'Family Guy', 'GOT']
内容的提问来源于stack exchange,提问作者Sri Ram
相关产品推荐
相关产品推荐

