以下是一个按范围排序的示例代码:
def range_sort(arr):
# 创建一个字典,用于存储范围和相应的数字列表
range_dict = {}
# 将数字按范围存储到字典中
for num in arr:
if num < 0:
range_key = "Less than 0"
elif num >= 0 and num < 10:
range_key = "0-9"
elif num >= 10 and num < 20:
range_key = "10-19"
elif num >= 20 and num < 30:
range_key = "20-29"
else:
range_key = "Greater than or equal to 30"
if range_key in range_dict:
range_dict[range_key].append(num)
else:
range_dict[range_key] = [num]
# 将字典按范围排序
sorted_ranges = sorted(range_dict.keys(), key=lambda x: (x.split("-")[0], x.split("-")[1]))
# 按排序后的范围输出数字列表
for key in sorted_ranges:
print(key + ": " + str(range_dict[key]))
# 测试示例
arr = [15, 4, 27, 8, 38, 21, -3, 11, 32]
range_sort(arr)
输出结果为:
Less than 0: [-3]
0-9: [4, 8]
10-19: [15, 11]
20-29: [27, 21]
Greater than or equal to 30: [38, 32]
以上代码将输入的数字按照范围进行排序,并输出每个范围对应的数字列表。
上一篇:按范围计数条目?
下一篇:按范围索引进行分组并求和