V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ithelloworld
V2EX  ›  程序员

python dict vs ruby hash

  •  
  •   ithelloworld · 2013-03-22 14:35:28 +08:00 · 2848 次点击
    这是一个创建于 4059 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ruby中hash

    grades = Hash.new
    grades["a"] << 1
    grades["b"] << 2
    grades["c"] << 3
    ...

    这样的用法,python用dict怎么实现?

    注意不是给一个key简单地赋值,而是要用 grades["a"] 装很多值。
    4 条回复    1970-01-01 08:00:00 +08:00
    binux
        1
    binux  
       2013-03-22 14:37:18 +08:00
    grades.setdefault("a", []).append(1)
    ithelloworld
        2
    ithelloworld  
    OP
       2013-03-22 14:54:52 +08:00
    @binux 以此类推,其它的值这样添加?

    grades.setdefault("b", []).append(2)
    grades.setdefault("c", []).append(3)
    orzfly
        3
    orzfly  
       2013-03-22 17:23:13 +08:00
    我怎么都觉得是Hash.new{[]}吧
    ithelloworld
        4
    ithelloworld  
    OP
       2013-03-22 17:33:51 +08:00
    @orzfly 你是说ruby的写法吗?应该是这样:

    Hash.new{|h, key| h[key] = []}
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2214 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:00 · PVG 18:00 · LAX 03:00 · JFK 06:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.