如何将 user_input() 的 table 存储到命名元组中

How to store a table of user_input(), into a named tuple

当输入类似 table 的数据时,如何将用户输入 () 存储到命名元组中

5

ID 标记名称 CLASS
1 97 雷蒙德 7
2 50 史蒂文 4
3 91 阿德里安 9
4 72 斯图尔特 5
5 80 彼得 6

以这个input()为例..

从 Python 3.7

开始,类似的东西应该可以工作
from typing import NamedTuple


class Student(NamedTuple):
    id_: int
    marks: int
    name: str
    class_: int


try:
    student = Student(*input().split())
except TypeError:
    print("error")

对于年龄较大的 Python,您必须以这种方式声明 namedtuple

from collections import namedtuple


Student = namedtuple('Student', ('id_', 'marks', 'name', 'class_', ))

如果您正在寻找列名的动态输入,可以使用以下代码

from collections import namedtuple
n = int(input())
Tot_mark = 0

for i in range(n+1):     
    if i == 0:
        s = ",".join(input().split())
        students = namedtuple('students',s)
    else:
        a,b,c,d = input().split()
        res = students(a,b,c,d)
        Tot_mark = Tot_mark + int(res.MARKS)
    
print(round(Tot_mark/n,2))