关于数组切片的解析:
① [i]、[-1];
② [:-1]、[:n]、[n:]、[n:m]、[:];
③ [n: m: x]、[: : x]、[: : ]、[-1: : ]、[: -1:]、[: :-1]
④ [a,b]、[a1:a2, b1:b2]
(-1在此相当于len(A)-1,即从首项至下标为 (len(A)-1)-1 的元素)
(-1在此相当于len(A)-1,即从下标为 len(A)-1 的元素至最后一项元素,实际上就是最后一项元素)
n和m都缺省时,范围为整个数组,元素的选择取决于步长
x为-1时,取步长为1的倒序
a表示取第一维的下标为a的元素,b表示取第二维的下标为b的元素
b1:b2表示取第二维的下标为b1至b2-1的数组切片。
当A[a1:a2, b1:b2]中有数值缺省时,规则同一维数组。
此外,更高维数组的切片以此类推。
arr = [1,2,3,6,1,6,8,1,9,7,5,1]coor, res= [], []
i = j = count = 0
for idx, num in enumerate(arr):
if num == 1:
if i==j:
i = idx
else:
if i<j:
i = idx
else:
j = idx
coor.append((i, j) if i < j else (j ,i))
for cr in sorted(set(coor) - {(0, 0)}):
res.append(arr[cr[0]:cr[1]+1])
print (res)
如果你用的Python2就把最后的print的括号去掉就行,Python3的话就不用
用另外一种方法弄了一下,可能更直观些,附上如下
arr = [1,2,3,6,1,6,8,1,9,7,5,1]coor, res= [], []
i = j = 0
idx = 1
while idx < len(arr):
while arr[idx]!=1:
idx += 1
if i==j:
i = idx
else:
if i < j:
i = idx
else:
j = idx
idx += 1
coor.append((i, j) if i<j else (j, i))
for cr in coor:
res.append(arr[cr[0]:cr[1]+1])
print(res)
你随便选一种就好,不过推荐后面的这种