|
本文内容
- General 一般
- Lists 列表
- Maps 映射
- Ranges/Slices 范围/片段
- Object access 对象访问
- 参考资料
Groovy 是一种基于 JVM 的敏捷开发语言,它结合了 Python、Ruby 和 Smalltalk 的许多强大的特性,Groovy 代码能够与 Java 代码很好地结合,也能用于扩展现有代码。由于其运行在 JVM 上的特性,Groovy 可以使用其他 Java 语言编写的库。
General
Python
| Groovy
| repr(x)
| x.inspect(), x.dump()
| x.y if x else None
| x?.y
| "%(foo)s" % locals()
| "${foo}"
|
Lists 列表
Python
| Groovy
| not x
| !x
x.empty
| len(x)
| x.size()
| for item, idx in enumerate(x): ...
| x.eachWithIndex { item, idx -> ... }
|
Maps 映射
Python
| Groovy
| {}
| [:] // an empty map
| Depends:
d if used like: for k in d:
list(d) if list needed
d[iter].keys() explicitly
| d.keySet()
| d.[iter]values()
| d.values()
| [k+1 for k in d]
| d.collect { k, v -> k+1 }
| d = dict(zip(k, v))
| k = 1..3
v = 'a'..'c'
d = [:]; k.eachWithIndex { it, i -> d[it] = v }
println d // [1:"a", 2:"b", 3:"c"]
|
Ranges/Slices 范围/片段
Python
| Groovy
| range(3)
| 0..<3
| range(1, 3+1)
| 1..3
| range(0, 10, 2)
| not represented as a data type but you can use
0.step(10, 2) {...}
| "abcdef"[3:]
| "abcdef"[3..-1]
|
Object access 对象访问
Python
| Groovy
| m = 'strip'; getattr(' ! ', m)()
| m = 'trim'; ' ! '."$m"()
| args = ('a', 2); 'abcabc'.find(*args)
| args = ['a', 2]; 'abcabc'.indexOf(*args)
| 参考资料
- Groovy Differences from Python
|
|
|