作者mantour (朱子)
看板Python
标题Re: [问题] 连续序列问题
时间Tue Feb 26 14:16:28 2008
※ 引述《plom (plom)》之铭言:
: 请问假设 List = [1,3,4,5,8.9], output: [(1),(3,4,5),(8,9)]
: 有没有什麽函式之类可以让连续的数字包在一起?
>>> List = [1,3,4,5,8,9]
>>> def f(L):
... if len(L)==0:
... return []
... count=0
... tmp=[[L[0]]]
... for num in L[1:]:
... if num==tmp[-1][-1]+1:
... tmp[count].append(num)
... else:
... tmp.append([num])
... count=count+1
... return [tuple(i) for i in tmp]
...
>>> f(List)
[(1,), (3, 4, 5), (8, 9)]
这样可以吗?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.213.158
※ 编辑: mantour 来自: 140.112.213.158 (02/26 14:19)