37,700
社区成员




def gather(seq,f):
return [[i for i in seq if f(i)==j] for j in set(map(f,seq))]
def gather(seq, f):
import collections
d = collections.defaultdict(list)
for x in seq:
d[f(x)].append(x)
return dict(d)
def gather(alist, fn):
tmp = []
for x in alist:
y = fn(x)
z = y + 1
w = len(tmp)
if w < z:
for i in range(w, z):
tmp.append([])
tmp[y].append(x)
return tmp
def gather(alist, fn):
tmp = []
for x in alist:
y = fn(x)
try:
t = tmp[y]
except:
z = y + 1
w = len(tmp)
if w < z:
for i in range(w, z):
tmp.append([])
tmp[y].append(x)
return tmp
def gather(seq, f):
d = {}
for x in seq:
y=f(x)
d[y]=d.get(y, [])+[x]
return d
>>> import itertools
>>> def gather(iterable, key=None):
data = sorted(iterable, key=key)
return [list(g) for k, g in itertools.groupby(data, key)]
>>> gather(range(10), lambda x: x%3)
[[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]
>>> gather(range(10), lambda x: x>3)
[[0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]
>>> gather(['a1','b2', 'c3', 'hello','bb'], lambda x: 'b' in x)
[['a1', 'c3', 'hello'], ['b2', 'bb']]
>>>
def gather(alist, fn):
tmax = 0
for x in alist:
y = fn(x)
if y > tmax:
tmax = y
tmp = [[] for i in range(tmax + 1)]
for x in alist:
y = fn(x)
tmp[y].append(x)
return tmp
def gather(alist, fn):
tmp = {}
for x in alist:
y = fn(x)
if y in tmp:
tmp[y].append(x)
else:
tmp[y] = [x]
return tmp
print gather(range(10), lambda x: x % 3)