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 年 5 月 27 日 · 3484 次点击
    这是一个创建于 4268 天前的主题,其中的信息可能已经有所发展或是发生改变。
    各位就当我闲的蛋疼,想问一下有没有办法在列表解析的时候同时输出下标。

    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 年 5 月 27 日
    cbsw
        3
    cbsw  
       2014 年 5 月 27 日   ❤️ 1
    [(i,j) for i, j in zip(lista, range(len(lista)))]
    dbow
        4
    dbow  
       2014 年 5 月 27 日
    这样: [(v, i) for i, v in enumerate(lista)]
    RIcter
        5
    RIcter  
       2014 年 5 月 28 日
    @dbow 这是正解。
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   1059 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:13 · PVG 02:13 · LAX 10:13 · JFK 13:13
    ♥ Do have faith in what you're doing.