I'm trying to write items from 3 different lists in a row (starting at 0), then going to a new line and writing the next set of items in the lists. eg 0, 1, 2, etc.
How do I wrap this up in some sort of loop that would do this? Is it something where I make a count, then replace each 0
in my code with the count
variable? I'm new to Python and coding in general and I'm struggling.
names = []
number_grades = []
letter_grades = []
def write_to_output():
file = open_file(output_grades, "w")
# I'm stuck here
file.write(str(names[0]) + ", " + str(number_grades[0]) + str(letter_grades[0]))
How do I loop through this and count up each loop, going through each item in the lists?
You can use zip
to iterate over multiple lists simultaneously:
names = ['Alice', 'Bob', 'Charlie']
number_grades = [4, 3, 2]
letter_grades = ['A', 'B', 'C']
with open('output.txt', 'w') as f:
for name, num, let in zip(names, number_grades, letter_grades):
f.write(f"{name}, {num} {let}\n")
Output ( output.txt
):
Alice, 4 A
Bob, 3 B
Charlie, 2 C
Alternative if you're not used to zip
- but you can always check zip documentation.
names = ['Alice', 'Bob', 'Charlie']
number_grades = [4, 3, 2]
letter_grades = ['A', 'B', 'C']
nbr_students = len(names)
with open('output.txt', 'w') as f:
for i in range(nbr_students):
f.write(f"{names[i]}, {number_grades[i]}, {letter_grades[i]}")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.