あれ、この言語でこれどうやって書くんだっけ? が頻発するので忘備録
記法
関数リテラル
es
const func1 = e => e + 1
const func2 = e => { return e }
python
func_1 = lambda x: x + 1
ruby
ほぼ無い。Procオブジェクトが近い
func_1 = lambda { |x| x + 1 }
func_2 = -> (x){ x + 1 }
func_3 = Proc.new { |x| x + 1 }
func_1.call(100)
文字列処理
置換
python
import re
re.sub(r'before', 'after', 'before_text')
'aaahoge'.replace('aa', 'bb')
マッチ
python
import re
re.match(r'hoge', 'hogefuga')
配列処理
参照
python
[][0] #=> IndexError: list index out of range
map
es
const hoge = [1, 2, 3].map(e => e + 1)
python
a = list(map(lambda x: x + 1, [1,2,3]))
a = [x + 1 for x in [1,2,3]]
map with index
python
list(map(lambda x: (x[0], x[1]), enumerate(['a', 'b', 'c'])))
#=> [(0, 'a'), (1, 'b'), (2, 'c')]
[(x, y) for x, y in enumerate(['a', 'b', 'c'])]
#=> [(0, 'a'), (1, 'b'), (2, 'c')]
reduce
es
python
from functools import reduce
reduce(lambda sum, x: sum + x, [1, 2, 3], 0)
sort
python
sorted([1,3,2])
sorted([1,3,2], reverse=True)
sorted("This is a test string from Andrew".split(), key=str.lower)
student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
sorted(student_objects, key=lambda student: student.age)
filter
python
list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5]))
[x for x in [1, 2, 3, 4, 5] if x % 2 == 0]
zip
python
list(zip(['a', 'b', 'c'], [1, 2, 3, 4]))
#=> [('a', 1), ('b', 2), ('c', 3)]
list(zip(['a', 'b', 'c'], [1, 2]))
#=> [('a', 1), ('b', 2)]
dict(zip(['a', 'b', 'c'], [1, 2, 3, 4]))
#=> {'a': 1, 'b': 2, 'c': 3}
Dictionaryの処理
dictionaryのmap_key
python
dict([['xx_' + x, y] for x, y in {'a': 1, 'b': 2}.items()])
dictionaryのfilter
python
for (key, value) in { 'id': 100, 'price': 50, 'unit': ''}.items():
if (key != 'id' and value):
print(key, value)
#=> price 50