Python列表查找值为6的索引时返回None的问题排查
问题分析与解决
你的代码输出None有两个核心问题:
函数未返回结果
函数throwing_6最后一行仅写了results,这只是引用变量,没有用return语句将结果返回。Python中,函数如果没有显式的return语句,默认会返回None,这就是你打印indexes得到None的直接原因。不必要的全局变量使用
你把results定义为全局变量,这会导致多次调用函数时,结果会累积在同一个列表里,引发意外行为(比如第二次调用函数时,列表里会保留第一次的结果)。
修正方案1:添加返回语句(保留全局变量)
results = [] def throwing_6(x): for index, throw in enumerate(x): if throw == 6: results.append(index) return results # 显式返回结果列表 indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6]) print(indexes) # 输出: [2, 4, 7]
修正方案2:使用局部变量(推荐)
将results定义为函数内部的局部变量,避免全局变量的副作用:
def throwing_6(x): results = [] for index, throw in enumerate(x): if throw == 6: results.append(index) return results indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6]) print(indexes) # 输出: [2, 4, 7]
更简洁的Pythonic写法
用列表推导式直接生成结果,代码更紧凑:
def throwing_6(x): return [idx for idx, val in enumerate(x) if val == 6] indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6]) print(indexes) # 输出: [2, 4, 7]
内容的提问来源于stack exchange,提问作者Kash
相关产品推荐
相关产品推荐

