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

讨论一个 Python 字典和列表推导式问题

  •  
  •   chevalier · May 19, 2016 · 3615 views
    This topic created in 3780 days ago, the information mentioned may be changed or developed.
    如有字典: d = {'x': 2, 'y': 3, 'z': 5}

    要得到列表:[('x', 1),('x', 2),('y', 1),('y', 2), ('y', 3),('z', 1),('z', 2),('z', 3),('z', 4),('z', 5)]

    我只能想到写法:
    L = []
    for a, n in d.iteritems():
    ....L += [(a, i) for i in range(1, n+1)]

    print L

    但总感觉还有更 pythonic 的写法,想不出来,不甘心,请教一下大家
    10 replies  •  2022-12-10 10:05:49 +08:00
    justfly
        1
    justfly  
       May 19, 2016
    sorted([(key, i+1) for key, value in d.items() for i in range(value)])
    wang9571
        2
    wang9571  
       May 19, 2016   ❤️ 3
    [(x, i) for x, y in d.items() for i in range(1, y + 1)]
    chevalier
        3
    chevalier  
    OP
       May 19, 2016
    为啥不能 append 了???
    想到了另外一种
    L=reduce(lambda x,y: x+y, [[(a, i) for i in range(1, n+1)] for a, n in d.iteritems()])
    chevalier
        4
    chevalier  
    OP
       May 19, 2016
    @wang9571 嗯,你的写法就是我想要的,多谢!
    felixzhu
        5
    felixzhu  
       May 19, 2016
    [(x, i) for x, y in d.iteritems() for i in xrange(1, y + 1)]
    holyzhou
        6
    holyzhou  
       May 20, 2016
    应该二楼的兼容性高点
    practicer
        7
    practicer  
       Jun 18, 2016
    我的方案是这样:
    from itertools import product

    l = []
    for k in d:
    l += list(product(k, range(1,d[k]+1)))
    antian
        8
    antian  
       Dec 10, 2022
    python 的 Iterable
    antian
        9
    antian  
       Dec 10, 2022
    d = {'x': 2, 'y': 3, 'z': 5}
    ls = []
    for i, j in d.items():
    # j 是一个迭代器
    for x in range(1, j + 1):
    ls.append((i, x))
    print(ls)
    分解下
    chevalier
        10
    chevalier  
    OP
       Dec 10, 2022
    @antian 六年都过去了,时光如梭 。。。我现在都转写 Golang 了 哈哈
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   885 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 22:22 · PVG 06:22 · LAX 15:22 · JFK 18:22
    ♥ Do have faith in what you're doing.