首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

写一个把列表分组的函数,该如何处理

2012-10-28 
写一个把列表分组的函数写一个函数,接受两个参数,第一个参数是列表,第二个是个函数,返回的是按照这个函数

写一个把列表分组的函数
写一个函数,接受两个参数,第一个参数是列表,第二个是个函数,返回的是按照这个函数作用到列表得到相同结果来分组的列表。比如:
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']]

[解决办法]
貌似用字典方式更方便:

Python code
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 tmpprint gather(range(10), lambda x: x % 3)
[解决办法]
试试itertools.groupby(iterable[, key])...
Python code
>>> 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']]>>>
[解决办法]
Python code
def gather(seq, f):    d = {}    for x in seq:        y=f(x)        d[y]=d.get(y, [])+[x]    return d
[解决办法]
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):                tmp.append([])        tmp[y].append(x)    return tmp
[解决办法]
Python code
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
[解决办法]
探讨

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

[解决办法]
Python code
def gather(seq,f):    return [[i for i in seq if f(i)==j] for j in set(map(f,seq))] 

热点排行