python dict vs ruby hash

2013-03-22 14:35:28 +08:00
 ithelloworld
ruby中hash

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

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

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

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

Hash.new{|h, key| h[key] = []}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/63726

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX