※ 引述《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)