LoginSignup
5
2

More than 3 years have passed since last update.

【Python】Python版lodashのpydashを試してみる

Last updated at Posted at 2020-03-08

Python版lodashのpydashを試してみる

TL;DR

会社ではフロントサイドをReact、バックエンドでDjangoで開発してるんですね。
フロントサイドではlodashというライブラリーをよく利用するんですが、めちゃくちゃく便利で、そのあとPythonを書くときに、lodashがないため、もどかしさを感じることがあります。
そんなもどかしさに苛まれているある日pydashというPython版lodashとも言えるlibraryを見つけたので紹介します。

インストール

利用できるPtyhonのバージョンは2.6以上、または3.3以上とのことなので、適当にPython 3.7.6で試すことにします。

$ pip install pydash

軽く触ってみる

>>> import pydash
>>> from pydash import flatten

# Arrays
>>> flatten([1, 2, [3, [4, 5, [6, 7]]]])
[1, 2, 3, [4, 5, [6, 7]]]

>>> pydash.flatten_deep([1, 2, [3, [4, 5, [6, 7]]]])
[1, 2, 3, 4, 5, 6, 7]
>>> pydash.remove([{'name': 'moe', 'age': 40}, {'name': 'larry', 'age': 50}], lambda x: x['age'] < 50)
[{'name': 'moe', 'age': 40}]

# Collections
>>> pydash.map_([{'name': 'moe', 'age': 40}, {'name': 'larry', 'age': 50}], 'name')
['moe', 'larry']
>>> pydash.filter_([{'name': 'moe', 'age': 40}, {'name': 'larry', 'age': 50}], {'age': 40})
[{'name': 'moe', 'age': 40}]

# Functions
>>> curried = pydash.curry(lambda a, b, c: a + b + c)
>>> curried(1, 2)(3)
6

# Objects
>>> pydash.omit({'name': 'moe', 'age': 40}, 'age')
{'name': 'moe'}

# Utilities
>>> pydash.times(3, lambda index: index)
[0, 1, 2]

# Chaining
>>> pydash.chain([1, 2, 3, 4]).without(2, 3).reject(lambda x: x > 1).value()
[1]

すばらしいですね。
lodashと比べても遜色ないですね。

lodashとの違い

上記にもありますが、pydash.map_pydash.filter_など関数名に微妙に違いがあります。

最後に

かなり便利だと思います。
lodashのドキュメントはかなり読みやすいのでそちらを参考にしつつ開発が捗りそうです。

参考

https://pydash.readthedocs.io/en/latest/
https://lodash.com/

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2