Created
October 4, 2017 23:17
-
-
Save dev001hajipro/8ee4dae828fe78d334cfa437a0bf980b to your computer and use it in GitHub Desktop.
アスタリスクで、Pythonのリスト内表表記で、タプルからクラス型に変換する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding:utf-8 -*- | |
""" リスト内包表記で、タプルデータからクラス型で取り出す。""" | |
class Person: | |
def __init__(self, name, age: int, email): | |
self.name = name | |
self.age = age | |
self.email = email | |
def __repr__(self): | |
return self.__str__() | |
def __str__(self): | |
return "Person(" + self.name + ", " + str(self.age) + ", " + self.email | |
if __name__ == '__main__': | |
in_data = [ | |
("John Smith", 21, "john@company.com"), | |
("Alice Smith", 35, "alice@company.com"), | |
("Tom Smith", 42, "tom@company.com") | |
] | |
resultList = [] | |
for x in in_data: | |
resultList.append(Person(*x)) | |
print(resultList) | |
# リスト内包表記で、もっと簡単に書ける | |
resultList2 = [Person(*x) for x in in_data] | |
print(resultList2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment