3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでコレクション中のオブジェクトのメンバーのインデックス(メンバーをキーにした辞書)を作ってくれるラムダ式(修正)

Last updated at Posted at 2014-09-06

pythonでコレクション中のオブジェクトのメンバーのインデックス(メンバーをキーにした辞書)を作ってくれるラムダ式

import functools as f
makeindexes = lambda objects:{attr:{str(getattr(x,attr)):x for x in objects if attr in dir(x)} for attr in f.reduce(set.union,(set(y.__dict__.keys()) for y in objects if hasattr(y,"__dict__")),set())}

class A:
	def __init__(self,name):
		self.name = name
		self.id = id(self)

objs = [A(x) for x in ["tama","poti","mii"]]

indexes = makeindexes(objs)

print(indexes.keys())
#dict_keys(['id', 'name'])

print(indexes["name"]["poti"].name)
#poti

このままでは値がユニークでないとインデックス出来ないのでリストに包むことに。

mMakeindexes = lambda objects:{outer:f.reduce(lambda d,o:d[getattr(o,outer)].append(o) or d,objects,{getattr(obj,outer):[] for obj in objects if outer in dir(obj)}) for outer in f.reduce(set.union,(set(y.__dict__.keys()) for y in objects if hasattr(y,"__dict__")),set())}

objs = [A("poti") for x in range(5)]

indexes = mMakeindexes(objs)

print(indexes["name"]["poti"])
#[<__main__.A object at 0x7f0b4f2d7710>, <__main__.A object at 0x7f0b4f2d7790>] [<__main__.A object at 0x7f0b4f2d77d0>, <__main__.A object at 0x7f0b4f2d7850>]

うーむ、もっと綺麗に書けないものか

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?