1
wyntergreg 2016-12-13 09:03:22 +08:00
能。
|
2
bazingaterry 2016-12-13 09:16:55 +08:00 via iPhone
reduce?
|
3
Valyrian 2016-12-13 09:36:25 +08:00
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 。。 |
4
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]])] 方法和楼上类似,不推荐这么做,写完我都晕了 |
5
mgna17 2016-12-13 10:51:07 +08:00 1
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 res = reduce(func, l, []) 撸了个 reduce 版的😂 |
6
mgna17 2016-12-13 11:06:11 +08:00
@mgna17
缩进缩错了 - - ,改正 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 res = reduce(func, l, []) |
10
9hills 2016-12-13 13:51:09 +08:00
不要为了追求技巧。。就简简单单的 for 循环能搞定的事情。。。
a=[0,1,0,0,0,1,1,1,0,0,1] b=[] for i in a: __if b and b[-1][0] == i: ____b[-1].append(i) __else: ____b.append([i]) 可读性秒杀楼上方法 |
11
SakuraSa 2016-12-13 13:59:50 +08:00 8
似乎内置的 groupby 函数可以做这件事:
from itertools import groupby a = [0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1] b = [list(it) for key, it in groupby(a)] |
12
Magic347 2016-12-13 14:08:24 +08:00
def gen(l):
assert len(l) > 0 curr = l[0] cnt = 1 for i in range(1, len(l)): if l[i] == curr: cnt += 1 else: yield [curr] * cnt curr = l[i] cnt = 1 yield [curr] * cnt 得到 1 个生成器可供迭代 |
13
Magic347 2016-12-13 14:09:51 +08:00
def gen(l):
assert len(l) > 0 curr = l[0] cnt = 1 for i in range(1, len(l)): if l[i] == curr: cnt += 1 else: yield [curr] * cnt curr = l[i] cnt = 1 yield [curr] * cnt 得到 1 个生成器可供迭代 |