# 写一个把列表分组的函数

ws0309 2012-10-06 11:21:57

gather(range(10), lambda x: x%3)
[[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]

gather(range(10), lambda x: x>3)
[[4, 5, 6, 7, 8, 9],[0, 1, 2, 3]]

gather(['a1','b2', 'c3', 'hello','bb'], lambda x: 'b' in x)
[['b2', 'bb'], ['a1', 'c3', 'hello']]
...全文
228 11 打赏 收藏 转发到动态 举报

11 条回复

chyanog 2012-10-10
• 打赏
• 举报

``````
def gather(seq,f):
return [[i for i in seq if f(i)==j] for j in set(map(f,seq))]
``````
chyanog 2012-10-09
• 打赏
• 举报

``````
def gather(seq, f):
import collections
d = collections.defaultdict(list)
for x in seq:
d[f(x)].append(x)
return dict(d)
``````
ws0309 2012-10-08
• 打赏
• 举报

[Quote=引用 6 楼 的回复:]
Python code
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):
……
[/Quote]

qq120848369 2012-10-08
• 打赏
• 举报

[Quote=引用 4 楼 的回复:]

Python code
>>> import itertools
>>> def gather(iterable, key=None):
data = sorted(iterable, key=key)
return [list(g) for k, g in itertools.groupby(d……
[/Quote]

The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.

bugs2k 2012-10-07
• 打赏
• 举报

``````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``````
bugs2k 2012-10-07
• 打赏
• 举报

``````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``````
ws0309 2012-10-06
• 打赏
• 举报

chyanog 2012-10-06
• 打赏
• 举报

``````

def gather(seq, f):
d = {}
for x in seq:
y=f(x)
d[y]=d.get(y, [])+[x]
return d

``````
angel_su 2012-10-06
• 打赏
• 举报

``````>>> 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']]
>>>``````

bugs2k 2012-10-06
• 打赏
• 举报

``````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``````
bugs2k 2012-10-06
• 打赏
• 举报

``````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)``````

37,733

• 近7日
• 近30日
• 至今