* pythonのoperatorモジュールで,独自定義のデータリストから要素の値を取り出す
:CATEGORIES: python
operator --- 関数形式の標準演算子 — Python 3.8.6rc1 ドキュメント https://docs.python.org/ja/3/library/operator.html
上記のページを参考にやってみました。
```
```
class Lawyeries:
def __init__(self, user, name):
self.user = user
self.name = name
def __repr__(self):
return "%s:%s" % (self.user, self.name)
list = [Lawyeries('fukazawas','深澤諭史'), Lawyeries('motoken_tw', 'モトケン')]
list.append(Lawyeries('uwaaaa', '刑裁サイ太'))
for x in list:
key=operator.attrgetter('name')
print(key(x))
for x in list:
key=operator.attrgetter('user')
print(key(x))
```
```
>>> import operator
>>> class Lawyeries:
... def __init__(self, user, name):
... self.user = user
... self.name = name
... def __repr__(self):
... return "%s:%s" % (self.user, self.name)
...
>>> list = [Lawyeries('fukazawas','深澤諭史'), Lawyeries('motoken_tw', 'モトケン')]
>>> list.append(Lawyeries('uwaaaa', '刑裁サイ太'))
>>>
>>> for x in list:
... key=operator.attrgetter('name')
... print(key(x))
...
深澤諭史
モトケン
刑裁サイ太
>>> for x in list:
... key=operator.attrgetter('user')
... print(key(x))
...
fukazawas
motoken_tw
uwaaaa
>>>
```
0 件のコメント:
コメントを投稿