推荐学习书目
› 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
going
V2EX  ›  Python

Python 列表踢出某个元素上机作业题

  •  
  •   going · Dec 10, 2021 · 4416 views
    This topic created in 1756 days ago, the information mentioned may be changed or developed.

    请根据输入的原始列表,输出目标列表:

    原始列表:[1,2,None,None,None,None,None,None,3,4,5,6,None,None,None,None,7,8,9,10]

    目标列表: [1,2] [3,4,5,6] [7,8,9,10]

    14 replies  •  2021-12-11 04:25:50 +08:00
    princelai
        1
    princelai  
       Dec 10, 2021   ❤️ 2
    from itertools import groupby

    [list(g[1]) for g in groupby(ll,key=lambda x:x is not None) if g[0]]
    going
        2
    going  
    OP
       Dec 10, 2021
    @princelai 厉害
    learningman
        3
    learningman  
       Dec 10, 2021   ❤️ 3
    建议自己的作业自己写,楼上那哥们 pythonic 的写法你能理解吗
    ma6254
        4
    ma6254  
       Dec 10, 2021
    自己的作业自己写(滑稽
    deplivesb
        5
    deplivesb  
       Dec 10, 2021
    v2 已经沦陷为百度知道了吗
    stimw
        6
    stimw  
       Dec 10, 2021 via Android
    为什么大半年前就在问作业了...大半年后还停留在这种问题
    bytesfold
        7
    bytesfold  
       Dec 10, 2021   ❤️ 1
    @learningman 并不觉得 pythonic ,如果是公司代码不加备注基本无法维护
    JasonEWNL
        8
    JasonEWNL  
       Dec 10, 2021
    @deplivesb 高级点,Way to Overflow 。(

    @going 话说回来鉴于是作业,或可回归不依赖任何库的一般思路,日后有机会亦能写出不一定最具效率但较易维护的代码。

    ```
    il = [1, 2, None, None, None, None, None, None, 3, 4, 5, 6, None, None, None, None, 7, 8, 9, 10]
    ol = [[]]
    for i in il:
    if i:
    ol[-1].append(i)
    elif ol[-1]:
    ol.append([])
    print(ol) # [[1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
    ```
    keepeye
        9
    keepeye  
       Dec 10, 2021
    遍历一遍不就可以了吗?这题是送分题
    cnrting
        10
    cnrting  
       Dec 10, 2021 via iPhone   ❤️ 1
    print(il[0:2],il[8:12],il[16:20]) 🐶
    raycool
        11
    raycool  
       Dec 10, 2021
    @princelai 学习了,以前还真少用这个 groupby
    fml87
        12
    fml87  
       Dec 10, 2021
    lst = [1,2,None,None,None,None,None,None,3,4,5,6,None,None,None,None,7,8,9,10]

    [*map(eval,re.split(",,+",re.sub("[^0-9,]", "",str(lst) )))]
    28Sv0ngQfIE7Yloe
        13
    28Sv0ngQfIE7Yloe  
       Dec 10, 2021   ❤️ 1
    为啥我感觉 op 没有提问的礼貌
    szxczyc
        14
    szxczyc  
       Dec 11, 2021
    @cnrting 哈哈哈哈哈~能把我笑死
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2697 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 03:35 · PVG 11:35 · LAX 20:35 · JFK 23:35
    ♥ Do have faith in what you're doing.