Skip to content

Instantly share code, notes, and snippets.

@dev001hajipro
Created October 4, 2017 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev001hajipro/8ee4dae828fe78d334cfa437a0bf980b to your computer and use it in GitHub Desktop.
Save dev001hajipro/8ee4dae828fe78d334cfa437a0bf980b to your computer and use it in GitHub Desktop.
アスタリスクで、Pythonのリスト内表表記で、タプルからクラス型に変換する
# -*- 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