推荐学习书目
› 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 · 2472 views
    This topic created in 3021 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
    Inkway
    Aug 14, 2018❤️2
    1
    finallist = listB[1::2]
    vipppppp
    vipppppp
    Aug 15, 2018
    2
    思考了一下,觉得还是写 for 循环靠谱。。。
    final_list = [a[i] for i in range(min(len(a), len(b))) if b[i] == 1]
    vipppppp
    vipppppp
    Aug 15, 2018
    3
    a,b 数组写反了 T_T
    mayorbryant
    mayorbryant
    Aug 15, 2018
    4
    试试
    map(lambda y: y[1], filter(lambda x: x[0] == 1, zip(a, b)))

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

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