找出列表中的连续元素
比如:
{3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46}
怎么得到下面的结果呢?
{{3,7},{10,12},{15,17},{19,24},{42,46}} python 列表 list split
[解决办法]
def findSequence(inputList):
lastVal = inputList[0]
retval = []
tmpList = []
for index,value in enumerate(inputList):
currentVal = inputList[index]
if 0 == index:
tmpList.append(currentVal)
continue
else:
if currentVal - lastVal == 1:
tmpList.append(currentVal)
else:
retval.append(tmpList)
tmpList = []
tmpList.append(currentVal)
lastVal = currentVal
if len(tmpList) != 0:
retval.append(tmpList)
return retval
if __name__ == "__main__":
l = [3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46]
result = findSequence(l)
print result
[解决办法]
def Find(lst, result):
last = first = lst.pop(0)
while len(lst):
value = lst.pop(0)
if value != last + 1:
result.append([first, last])
last = first = value
else:
last = value
result.append([first, last])
l = [3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46]
r = []
Find(l, r)
print r
def Find(lst, result):
last = first = lst[0]
for i in range(1, len(lst)):
value = lst[i]
if value != last + 1:
result.append([first, last])
last = first = value
else:
last = value
result.append([first, last])
def Find(lst):
result = []
result_after = [value for value in lst if not value + 1 in lst]
for after in result_after:
before = after
while(before in lst):
before = before - 1
result.append([before + 1, after])
return result
l = [3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46]
result = Find(l)
print result
def find(L):
first = last = L[0]
result = []
for i in L[1:]:
if i == last + 1:
last = i
else:
result.append((first, last))
first = last = i
result.append((first, L[-1]))
return result
if __name__ == '__main__':
input = {1,3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46, 60}
result = find(list(input))
print(result)