推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
aheadlead
V2EX  ›  Python

有无可以对容器分类的库或函数?

  •  
  •   aheadlead · Sep 8, 2017 · 3117 views
    This topic created in 3192 days ago, the information mentioned may be changed or developed.

    比如说,我有一个 list

    >>> l = [2, 3, 4, 5, 2, 3, 4, 2, 6, 4, 3]
    

    我还有一个函数

    >>> fn = lambda x: x%2 
    

    我想根据把 l 的每个元素作用到函数 fn 上
    根据其返回值分类

    >>> SOME_FUNCTION(fn, l)
    {
        0: [2, 4, 2, 4, 2, 6, 4],
        1: [3, 5, 3, 3]
    }
    

    有这种工具吗? (虽然写一个也不麻烦)
    感谢

    5 replies    2017-09-08 23:08:43 +08:00
    newlife
        1
    newlife  
       Sep 8, 2017
    没有
    lishunan246
        2
    lishunan246  
       Sep 8, 2017
    d = {}
    for x in l:
    r = f(x)
    if r in d:
    d[r].append(x)
    else:
    d[r] = [x]
    这样?
    aheadlead
        3
    aheadlead  
    OP
       Sep 8, 2017
    @lishunan246
    . def classify(classifier, container):
    . ret = defaultdict(list)
    . for i in container:
    . ret[classifier(i)].append(i)
    . return ret
    guyskk
        4
    guyskk  
       Sep 8, 2017 via Android   ❤️ 1
    itertools.groupby
    NoAnyLove
        5
    NoAnyLove  
       Sep 8, 2017   ❤️ 1
    听你的需求像是 itertools.groupby,但是 group 要求先对数据进行 sort,不然会产生多组相同 key 的结果
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3207 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 03:03 · PVG 11:03 · LAX 20:03 · JFK 23:03
    ♥ Do have faith in what you're doing.