I feel like this is gonna get downvotes, but I can’t think anymore. I have a function that prints a sorted list of students from a CSV file, but it obviously prints it as a list of tuples. Is there a way I can change the code so that every line gets printed separetely? I tried adding sep="\n" or "\n" on its own and it does not work. Sorry the code is partly in polish. I tried looking it up on google, but found nothing. I also cannot use any libraries.
def sortowanie():
print("Wybierz opcje sortowania listy studentów:")
print("""
1. Wyświetl dane o studentach posortowane po ocenach malejąco.
2. Wyświetl studentów w porządku alfabetycznym.
3. Wyświetl dane o studentach posortowane po numerach albumów rosnąco.
4. Wyświetl dane studenta z najwyższą oceną.
5. Wyświetl studenta z najniższą oceną.
""")
with open('students.csv') as f:
lines = f.read().splitlines()
lines = [line.split(',') for line in lines]
students = [(n, s, int(nu), float(g)) for (n, s, nu, g) in lines]
for x in students:
try:
y = int(input("Wybrana opcja > "))
except ValueError:
print("Proszę wybrać poprawny numer.")
if y == 1:
print(sorted(students, key=lambda s: s[3], reverse=True))
if y == 2:
print(sorted(students, key=lambda s: s[1]))
if y == 3:
print(sorted(students, key=lambda s: s[2]))
if y == 4:
print(max(students, key=lambda s: s[3]))
if y == 5:
print(min(students, key=lambda s: s[3]))
else:
break
break
sortowanie()
>Solution :
This should do it:
def sortowanie():
print("Wybierz opcje sortowania listy studentów:")
print("""
1. Wyświetl dane o studentach posortowane po ocenach malejąco.
2. Wyświetl studentów w porządku alfabetycznym.
3. Wyświetl dane o studentach posortowane po numerach albumów rosnąco.
4. Wyświetl dane studenta z najwyższą oceną.
5. Wyświetl studenta z najniższą oceną.
""")
with open('students.csv') as f:
lines = f.read().splitlines()
lines = [line.split(',') for line in lines]
students = [(n, s, int(nu), float(g)) for (n, s, nu, g) in lines]
for x in students:
try:
y = int(input("Wybrana opcja > "))
except ValueError:
print("Proszę wybrać poprawny numer.")
if y == 1:
[print(x) for x in sorted(students, key=lambda s: s[3], reverse=True)]
if y == 2:
[print(x) for x in sorted(students, key=lambda s: s[1])]
if y == 3:
[print(x) for x in sorted(students, key=lambda s: s[2])]
if y == 4:
print(max(students, key=lambda s: s[3]))
if y == 5:
print(min(students, key=lambda s: s[3]))
else:
break
break
sortowanie()
Instead of printing the list, you can use a comprehension to print each item in the list separately, and default behavior of print is to end with a newline.