1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

構造体の作成 (paizaランク C 相当)

Last updated at Posted at 2024-10-28

解答は見てくれを表示するだけで、全然構造体を作成してませんでした。

N=int(input())
ulist=[]
for i in range(N):
    n,o,b,s=input().split()
    #入力を元に辞書を作成
    u = {
        "nickname":n,
        "old":o,
        "birth":b,
        "state":s,
    }
    #辞書をリストに追加
    ulist.append(u)

for u in ulist:
    print("User{")
    for key, value in u.items():
        #キーと値を出力
        print(f"{key} : {value}")
    print("}")

構造体ならばulist[0].nicknameのような感じで使いたいので、調べたところ、namedtapleやdataclassを使用すればいいとのこと

from dataclasses import dataclass

# dataclassの定義
@dataclass
class User:
    nickname:str
    old:str
    birth:str
    state:str
    
N = int(input())
ulist = []

# 入力を取得し、インスタンスをリストに追加
for i in range(N):
    n, o, b, s = input().split()
    u = User(nickname=n, old=o, birth=b, state=s)
    ulist.append(u)
# リストの内容を出力
for u in ulist:
    print("User{")
    for key, value in u.__dict__.items():
        print(f"{key} : {value}")
    print("}")

結果表示の関係で辞書型に変換して出力してますが、
print(ulist[0].nickname)
といった感じに取り扱えます。

1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?