subjects = ["Algorithms", "Software Design", "Poetry", "Electronics"]
grades = ["98", "88", "85", "90"]
print("Course ", " Score")
gradebook = zip(subjects, grades)
for subject, grade in gradebook: #for creating a table
print(subject, '\t', grade)
print('\n')
grade_book = list(gradebook)
list(grade_book[2]).remove('85')
list(grade_book[2]).append('Pass')
Here I have a sublist as ['Poetry', '85'], and I have to delete the grade(85) by using remove() and by using the.append() add a new "Pass" value to the sublist where the 85 is located. I tried it in the last two lines, but it didn't work out.
zip return a list of tuple. Once a tuple is created, you cannot change its values.
You can convert the list of tuples into a list of lists instead and the edit
grade_book = [list(elem) for elem in gradebook]
grade_book[2][1] = 'Pass'
If you need to convert back to a list of tuples you can do so like this
grade_book = [(x,y) for [x,y] in grade_book]
A dictionary might also be a nice option here.
zip(subjects, grades)
returns an iterator. By looping through gradebook
you already "use up" all the values in the iterator. That's why grade_book = list(gradebook)
returns an empty list, thus making the following operations invalid.
I would also suggest to use a dictionary here, like so:
subjects = ["Algorithms", "Software Design", "Poetry", "Electronics"]
grades = ["98", "88", "85", "90"]
gradebook = dict(zip(subjects, grades))
print("Course ", " Score")
for subject, grade in gradebook.items(): # for creating a table
print(subject, '\t', grade)
print()
Then you can easily add new elements and use.pop() to remove elements:
gradebook.pop('Poetry')
gradebook["Pass"] = "85"
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.