python 10道 中等难度 编程

时间:2025-01-14 07:08:13
  • def compress_range(lst):
  • result = []
  • start, end = lst[0], lst[0]
  • for num in lst[1:]:
  • if num == end + 1:
  • end = num
  • else:
  • if start == end:
  • (str(start))
  • else:
  • (f"{start}-{end}")
  • start, end = num, num
  • if start == end:
  • (str(start))
  • else:
  • (f"{start}-{end}")
  • return result
  • my_list = [1, 2, 3, 5, 6, 7, 10, 11, 12]
  • compressed = compress_range(my_list)
  • print("压缩后的范围列表:", compressed)