V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2018-08-14 16:53:41 +08:00 · 1449 次点击
    这是一个创建于 2081 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    7 条回复    2018-08-15 19:01:44 +08:00
    YehShs
        1
    YehShs  
       2018-08-14 20:06:30 +08:00   ❤️ 2
    finallist = listB[1::2]
    vipppppp
        2
    vipppppp  
       2018-08-15 09:42:31 +08:00
    思考了一下,觉得还是写 for 循环靠谱。。。
    final_list = [a[i] for i in range(min(len(a), len(b))) if b[i] == 1]
    vipppppp
        3
    vipppppp  
       2018-08-15 09:43:06 +08:00
    a,b 数组写反了 T_T
    mayorbryant
        4
    mayorbryant  
       2018-08-15 18:23:21 +08:00
    试试
    map(lambda y: y[1], filter(lambda x: x[0] == 1, zip(a, b)))

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

    # 取偶数位
    b[0::2]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5075 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 01:17 · PVG 09:17 · LAX 18:17 · JFK 21:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.