l = [0,1,0,0,0,1,1,1,0,0,1] l1 = [(l[i], i) for i in xrange(len(l)) if i == len(l) - 1 or l[i] != l[i+1]] l2 = [([l1[i][0]] * (l1[i][1] + 1 if i == 0 else l1[i][1] - l1[i-1][1])) for i in xrange(len(l1))]
根本不值得这样写,可读性为 0 。。
princelai
2016-12-13 10:39:23 +08:00
l = [0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1]
[[l[j]]*(i-j) for i,j in zip([i for i in range(len(l)) if l[i] != l[i-1]][1:] + [len(l)] , [i for i in range(len(l)) if l[i] != l[i-1]])]
方法和楼上类似,不推荐这么做,写完我都晕了
mgna17
2016-12-13 10:51:07 +08:00
l = [0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1]
def func(x, y): try: if x[-1][-1] != y: x.append([y]) else: x[-1].append(y) except IndexError: x.append([y]) return x