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
jianghu52
V2EX  ›  Python

用列表解析的时候可以输出下标么

  •  
  •   jianghu52 · 2014-05-27 20:50:38 +08:00 · 2983 次点击
    这是一个创建于 3593 天前的主题,其中的信息可能已经有所发展或是发生改变。
    各位就当我闲的蛋疼,想问一下有没有办法在列表解析的时候同时输出下标。

    lista = ['a', 'b', 'c']
    print [x for x in lista]

    此时输出的还是 ['a', 'b', 'c']
    我希望输出的是 [('a', 0), ('b', 1), ('c', 2)]
    请问有什么办法
    5 条回复    2014-05-28 08:15:24 +08:00
    jiang42
        2
    jiang42  
       2014-05-27 22:33:22 +08:00
    cbsw
        3
    cbsw  
       2014-05-27 23:06:33 +08:00   ❤️ 1
    [(i,j) for i, j in zip(lista, range(len(lista)))]
    dbow
        4
    dbow  
       2014-05-27 23:36:39 +08:00
    这样: [(v, i) for i, v in enumerate(lista)]
    RIcter
        5
    RIcter  
       2014-05-28 08:15:24 +08:00
    @dbow 这是正解。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2786 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:28 · PVG 20:28 · LAX 05:28 · JFK 08:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.