Give a line read of the file and end with '\n'3,5,1,12,2,1,1,5,4,4,yes\n
first eliminated the whitespaces with strip() and then we divided it into its components with split(","). This produces a list of strings, some of which represent numerical values.We can create a new list using list compression, but instead of copying the element such as, we use a conditional expression that first checks if the element is numerical (and converts it). If it is not numerical, it is copied as well.In Python conditional conversion can be traditionally written as follows:if x.isnumeric():
valor = int(x)
else:
valor = x
or in its compact form, similar to the ternary operator ?: C/C++, in one line:valor = int(x) if x.isnumeric() else x
with which the solution is:datos = []
with open("archivo.data", "r") as data:
for linea in data:
valores = [int(x) if x.isnumeric() else x for x in linea.strip().split(",")]
datos.append(valores)
print(datos)
produces:[[3, 5, 1, 12, 2, 1, 1, 5, 4, 4, 'yes'], [1, 11, 2, 8, 4, 12, 4, 9, 1, 2, 'no'], [1, 5, 1, 11, 1, 12, 1, 8, 2, 4, 'yes'], [2, 3, 1, 7, 1, 10, 1, 9, 2, 9, 'no'], [2, 12, 3, 7, 2, 6, 4, 13, 2, 7, 'no']]
If you want to read decimals, you can use float instead of intEditionIt is possible to cut the code even further. While it is shortened and works, it loses a bit in legibility.In any case, here it is:datos = []
with open("archivo.data", "r") as data:
datos = [[int(x) if x.isnumeric() else x for x in linea.strip().split(",")] for linea in data.readlines()]
print(datos)