Collections.namedtuple() Python の練習問題

Nov 28 2022
collections.namedtuple() 基本的に、namedtuple は簡単に作成できる軽量のオブジェクト タイプです。

collections.namedtuple()
基本的に、namedtuple は簡単に作成できる軽量のオブジェクト タイプです。
これらは、タプルを単純なタスク用の便利なコンテナーに変えます。

名前付きタプルでは、​​タプルのメンバーにアクセスするために整数インデックスを使用する必要はありません。

例 :

コード 01

>>> from collections import namedtuple
>>> Point = namedtuple('Point','x,y')
>>> pt1 = Point(1,2)
>>> pt2 = Point(3,4)
>>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y )
>>> print dot_product
11

>>> from collections import namedtuple
>>> Car = namedtuple('Car','Price Mileage Colour Class')
>>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y')
>>> print xyz
Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y')
>>> print xyz.Class
Y

Dr. John Wesley は、生徒の ID、マーク、クラス、名前のリストを含むスプレッドシートを持っています。
あなたの仕事は、ウェズリー博士が学生の平均点を計算するのを手伝うことです。

ノート:

1. 列の順序は任意です。ID、マーク、クラス、および名前は、スプレッドシートに任意の順序で書き込むことができます。

2. 列名は、ID、MARKS、CLASS、および NAME です。(これらの名前のスペルと大文字と小文字のタイプは変更されません。)

入力フォーマット:

最初の行には、学生の総数である整数 N が含まれています。
2 行目には、列の名前が任意の順序で含まれています。

次の N 行には、それぞれの列名の下に、マーク、ID、名前、およびクラスが含まれています。

制約 :

  • 0 <= N <= 100

小数点以下 2 桁に修正されたリストの平均点を出力します。

サンプル入力:

テストケース 01

5
ID         MARKS      NAME       CLASS     
1          97         Raymond    7         
2          50         Steven     4         
3          91         Adrian     9         
4          72         Stewart    5         
5          80         Peter      6

5
MARKS      CLASS      NAME       ID        
92         2          Calum      1         
82         5          Scott      2         
94         2          Jason      3         
55         8          Glenn      4         
82         2          Fergus     5

テストケース 01

78.00

81.00

テストケース 01

平均 = (97 + 50 + 91 + 72 + 80)/5

この課題を 4 行以下のコードで解決できますか?

注: 解は正しいが 4 行以上ある場合、ペナルティはありません。

解決

import collections

n = int(input())
scol = ','.join(input().split())
Student = collections.namedtuple('Student',scol)

sum = 0
for i in range(n):
    row = input().split()
    student = Student(*row)
    sum += int(student.MARKS)

print(sum/n)