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[i] }
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) |
Labels
(None)
Comments (1)
Aug 24, 2007
Mike says:
These examples are wrong: d.iterkeys() d.itervalues() k1 for k,v in d.iteritem...These examples are wrong:
d.[iter]keys()
d.[iter]values()
[k+1 for k,v in d.iteritems()]
Should be:
d.keys()
d.values()
[k for k,v in d.items()]