Python四分位数计算问题求助:Q1/Q3计算结果异常
我编写了一段Python代码用于计算数字列表的第一四分位数(Q1)和第三四分位数(Q3),输入1,2,3,4,5,6时结果正确(Q1=2、Q3=5),但输入1,2,3,4,5,6,7,8,9,10时得到错误结果Q1=2、Q3=7,相关代码如下:
def quartiles(user_input): user_input.sort() length = len(user_input) # Initialize Values if length % 2 == 0: section_one = user_input[:(length // 2)] section_three = user_input[(length // 2):] else: section_one = user_input[:(length // 2)] section_three = user_input[(length // 2) + 1:] one_length = len(section_one) three_length = len(section_three) # Calculate Quartiles if one_length % 2 == 0: q1 = (section_one[one_length // 2 - 1] + section_one[one_length // 2]) / 2 else: q1 = section_one[one_length // 2] if three_length % 2 == 0: q3 = (section_three[three_length // 2 - 1] + section_three[three_length // 2]) / 2 else: q3 = section_three[three_length // 2] return q1, q3 q1, q3 = quartiles(user_input) print("First Quartile:", q1) time.sleep(0.05) print("Third Quartile:", q3)
问题根源
你得到错误结果的核心原因是输入数据未正确转换为整数列表,直接传入了字符串形式的列表。当对字符串列表排序时,会按字典序排序(比如"10"会排在"2"前面),导致分块后的section_one和section_three内容完全错误,最终计算出不符合预期的四分位数。
举个例子:输入字符串"1,2,3,4,5,6,7,8,9,10",如果直接分割成字符串列表["1","2","3","4","5","6","7","8","9","10"],排序后会变成["1","10","2","3","4","5","6","7","8","9"]。此时section_one是前5个元素["1","10","2","3","4"],计算Q1时取索引2的元素"2";section_three是后5个元素["5","6","7","8","9"],取索引2的元素"7",正好是你遇到的错误结果。
另外,原代码直接修改传入的user_input列表(调用user_input.sort()),会产生副作用,建议改用sorted()生成新的排序列表。
修正方案
1. 完善输入处理逻辑
先将用户输入的字符串分割并转换为整数列表,再传入计算函数:
user_input_str = input("请输入数字列表,用逗号分隔:") user_input = list(map(int, user_input_str.split(',')))
2. 修正后的完整代码
def quartiles(user_input): # 生成排序后的新列表,避免修改原输入 sorted_list = sorted(user_input) length = len(sorted_list) mid = length // 2 # 分割前后半部分(采用常用的Tukey's hinges方法) if length % 2 == 0: lower_half = sorted_list[:mid] upper_half = sorted_list[mid:] else: lower_half = sorted_list[:mid] upper_half = sorted_list[mid+1:] # 计算Q1 n_lower = len(lower_half) if n_lower % 2 == 0: q1 = (lower_half[n_lower//2 - 1] + lower_half[n_lower//2]) / 2 else: q1 = lower_half[n_lower//2] # 计算Q3 n_upper = len(upper_half) if n_upper % 2 == 0: q3 = (upper_half[n_upper//2 - 1] + upper_half[n_upper//2]) / 2 else: q3 = upper_half[n_upper//2] return q1, q3 # 输入处理 user_input_str = input("请输入数字列表,用逗号分隔:") user_input = list(map(int, user_input_str.split(','))) q1, q3 = quartiles(user_input) print("第一四分位数(Q1):", q1) print("第三四分位数(Q3):", q3)
测试结果
输入1,2,3,4,5,6,7,8,9,10,会得到正确结果:Q1=3,Q3=8;输入1,2,3,4,5,6,结果依然为Q1=2,Q3=5,符合预期。
内容的提问来源于stack exchange,提问作者Jimmy

