-1
from collections import namedtuple
Data=namedtuple('Data','name number age cgpa')#best to keep all data types as string
def prettyprint(X,end="\n"):
    s="{0},{1},{2},{3}".format(X.name,X.number,X.age,X.cgpa)
    print(s,end=end)
file_name=r"""C:\Users\DELL\OneDrive\Desktop\Students Data.txt"""
file=open(file_name,'r')
List=[]
for i in file.readlines():
    temp=[j.rstrip().lstrip() for j in i.split(',')]
    List.append(tuple(temp))
Students=list(map(lambda x:Data(*x),List))
Sort_cgpa=sorted(Students,key=lambda x:(float(x.cgpa),x.name,int(x.number[-4:]),int(x.age)),reverse=True)
for out in Sort_cgpa:
    prettyprint(out)

Students Data.txt contains the data of the students in Name, Number, Age, CGPA. Thing is I will be using age as int and cgpa as float variables I have no issues to use all the data types as string and convert the data type to needed any time I want to. So, is the best way to use namedtuple as a single datatype like string.

Note that while I can change

temp_new=[[i[0],i[1],int(i[2]),float(i[3])] for i in temp]
List.append(temp_new)

My question isn't specific to this code I want to know is there a way to change init(self) in the so that I can use self.age=int(self.age) or it is best to use all the datatypes as string

Soham Patil
  • 111
  • 3
  • unfortunately, it's [unclear](https://idownvotedbecau.se/unclearquestion) to me what you're asking. if possible can you clarify, whats the ask here? – rv.kvetch Jan 07 '22 at 17:38
  • @rv.kvetch I'm sorry if my question was unclear but I got my answer from the answer, my question was to convert the data type in the class of namedtuple and not want to do it manually everytime – Soham Patil Jan 09 '22 at 05:46
  • Regardless if someone answers your question correctly and it gets up getting accepted, you should still strive to ask questions that are unambiguous and easy for others to understand. At the moment the question itself is unfortunately a mess and I still cannot understand the specific ask which was the purpose of the question. That is, I don’t understand the question here being asked. If possible would appreciate an edit above for clarification sake. – rv.kvetch Jan 10 '22 at 00:25

1 Answers1

2

If you want to be able to convert the input values automatically, I would use a dataclass rather than a namedtuple. The docs are here: https://docs.python.org/3/library/dataclasses.html

If you define a dataclass, you can override a method named __post_init__. This gets called automatically after the init method is run.

from dataclasses import dataclass

@dataclass
class Student:
    name: str
    number: int
    age: int
    cgpa: int

    def __post_init__(self):
        self.age = int(self.age)

Using the Student class, you can see the age now gets converted

>>> Student("Joe", "10", "12", "4.0")
Student(name='Joe', number='10', age=12, cgpa='4.0')
Brad Campbell
  • 2,969
  • 2
  • 23
  • 21