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

两个 list 操作问题

  •  
  •   MiracleTony · Aug 14, 2018 · 2322 views
    This topic created in 2970 days ago, the information mentioned may be changed or developed.

    listA = [0,1,0,1....0,1] listB = ['A','B','C'....'An','Bn'] 结果是 finallist = ['B','D'...'Bn'] 就是根据 listA 为 1 的值 对应选出 listB 的值,不用 for 循环,怎么写效率最高

    7 replies  •  2018-08-15 19:01:44 +08:00
    Inkway
        1
    Inkway  
       Aug 14, 2018   ❤️ 2
    finallist = listB[1::2]
    vipppppp
        2
    vipppppp  
       Aug 15, 2018
    思考了一下,觉得还是写 for 循环靠谱。。。
    final_list = [a[i] for i in range(min(len(a), len(b))) if b[i] == 1]
    vipppppp
        3
    vipppppp  
       Aug 15, 2018
    a,b 数组写反了 T_T
    mayorbryant
        4
    mayorbryant  
       Aug 15, 2018
    试试
    map(lambda y: y[1], filter(lambda x: x[0] == 1, zip(a, b)))

    mayorbryant
        5
    mayorbryant  
       Aug 15, 2018
    上面那个 == 1 也可以去掉,主要是提醒你,如果想要 0 丢应的,就把 1 换成 0
    mayorbryant
        6
    mayorbryant  
       Aug 15, 2018
    当然,如果你的需求只是跳位取值的话,用 list 自带的步长是最简洁的
    # 取奇数位
    b[1::2]

    # 取偶数位
    b[0::2]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2469 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 02:58 · PVG 10:58 · LAX 19:58 · JFK 22:58
    ♥ Do have faith in what you're doing.