如何在嵌套列表的索引0位置查找最大值?
如何编写函数查找嵌套列表指定索引位置的最大值?
嘿,这个需求其实用Python的内置工具就能轻松解决,完全不用手动暴力挨个比对~ 我给你写个简洁又实用的函数,还会帮你拆解逻辑:
基础实现版本
先来看最核心的实现,思路很简单:先把所有子列表中对应索引的元素提取出来,再用内置的max()函数直接找最大值。
def max_at_index(nested_list, target_index): # 用列表推导式提取所有子列表中目标索引的元素 target_elements = [sublist[target_index] for sublist in nested_list] # 返回提取出的元素的最大值 return max(target_elements)
测试你的示例
拿你给出的数据来测试一下:
data = [[12345678, 14, 1],[135763365, 12, 0],[1234, 9, 0]] # 调用函数,指定要找索引0的最大值 result = max_at_index(data, 0) print(result) # 输出:135763365
更健壮的版本(处理边界情况)
如果担心有些子列表的长度不够,没法访问目标索引,可以加个前置检查,避免报错:
def max_at_index(nested_list, target_index): # 先遍历检查每个子列表是否能访问目标索引 for idx, sublist in enumerate(nested_list): if target_index >= len(sublist): raise ValueError(f"第 {idx} 个子列表长度为 {len(sublist)},无法访问索引 {target_index}") # 提取元素并返回最大值 target_elements = [sublist[target_index] for sublist in nested_list] return max(target_elements)
这样如果遇到比如[[1,2], [3]]这种情况,你要找索引1的最大值时,函数会直接抛出明确的错误提示,方便你排查问题。
内容的提问来源于stack exchange,提问作者zservies
相关产品推荐
相关产品推荐

