Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python从数字列表生成连续数字列表_Python_Python 3.x - Fatal编程技术网

Python从数字列表生成连续数字列表

Python从数字列表生成连续数字列表,python,python-3.x,Python,Python 3.x,我有一张这样的清单 List1 = [1,2,3,7,8,11,14,15,16] 我想用python生成一个新的列表 List2 = ["1:3", "7:8", "11", "14:16"] 我该怎么做,这里是循环选项 我不想使用For循环,因为我的列表中有30000个以上的数字。您可以使用生成器: List1 = [1,2,3,7,8,11,14,15,16] def groups(d): c, start = [d[0]], d[0] for i in d[1:]:

我有一张这样的清单

List1 = [1,2,3,7,8,11,14,15,16]
我想用python生成一个新的列表

List2 = ["1:3", "7:8", "11", "14:16"]
我该怎么做,这里是循环选项


我不想使用For循环,因为我的列表中有30000个以上的数字。

您可以使用生成器:

List1 = [1,2,3,7,8,11,14,15,16]
def groups(d):
  c, start = [d[0]], d[0]
  for i in d[1:]:
    if abs(i-start) != 1:
      yield c
      c = [i]
    else:
      c.append(i)
    start = i
  yield c

results = [str(a) if not b else f'{a}:{b[-1]}' for a, *b in groups(List1)]
输出:

['1:3', '7:8', '11', '14:16']

@ForceBru看到了这个问题,他完全忽略了我的案例中的11个。我不理解你的输出。这里有什么规定?您以7:8连续进行,但以1:3和14:16跳过元素。那么11自己离开?规则是1:3代表1,2,3和7:8代表7和8,而11没有12或10。因此,它仅为11。如果有10,那么它将是10:11,如果有12,那么它将是11:12,如果有10和12,那么它将是10:12。为什么不想使用for循环?你有什么办法可以循环浏览你的列表?无论如何,30000对于一个列表来说并不是那么大。在我的机器上循环这个列表需要0.000269秒