推荐学习书目
› 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 · 3747 views
    This topic created in 3827 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
    justfly
    May 19, 2016
    1
    sorted([(key, i+1) for key, value in d.items() for i in range(value)])
    wang9571
    wang9571
    May 19, 2016❤️3
    2
    [(x, i) for x, y in d.items() for i in range(1, y + 1)]
    chevalier
    chevalier
    OP
    May 19, 2016
    3
    为啥不能 append 了???
    想到了另外一种
    L=reduce(lambda x,y: x+y, [[(a, i) for i in range(1, n+1)] for a, n in d.iteritems()])
    chevalier
    chevalier
    OP
    May 19, 2016
    4
    @wang9571 嗯,你的写法就是我想要的,多谢!
    felixzhu
    felixzhu
    May 19, 2016
    5
    [(x, i) for x, y in d.iteritems() for i in xrange(1, y + 1)]
    holyzhou
    holyzhou
    May 20, 2016
    6
    应该二楼的兼容性高点
    practicer
    practicer
    Jun 18, 2016
    7
    我的方案是这样:
    from itertools import product

    l = []
    for k in d:
    l += list(product(k, range(1,d[k]+1)))
    antian
    antian
    Dec 10, 2022
    8
    python 的 Iterable
    antian
    antian
    Dec 10, 2022
    9
    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
    chevalier
    OP
    Dec 10, 2022
    10
    @antian 六年都过去了,时光如梭 。。。我现在都转写 Golang 了 哈哈
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2336 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:14 · PVG 08:14 · LAX 16:14 · JFK 19:14
    ♥ Do have faith in what you're doing.