简体   繁体   English

用 python 中的新元素 using.remove() 和.append() 替换子列表元素之一

[英]replacing one of the sublist element with new element using .remove() and .append() in python

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.在这里,我有一个子列表为 ['Poetry', '85'],我必须使用 remove() 删除等级(85),并使用.append() 将新的“通过”值添加到子列表中85位于。 I tried it in the last two lines, but it didn't work out.我在最后两行尝试过,但没有成功。

zip return a list of tuple. zip 返回一个元组列表。 Once a tuple is created, you cannot change its values.创建元组后,您无法更改其值。

  1. create a new tuple, and replace it创建一个新元组,并替换它
  2. turn it to a list, change, re-tuple it把它变成一个列表,改变,重新组合它

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. zip(subjects, grades)返回一个迭代器。 By looping through gradebook you already "use up" all the values in the iterator.通过遍历gradebook ,您已经“用尽”了迭代器中的所有值。 That's why grade_book = list(gradebook) returns an empty list, thus making the following operations invalid.这就是为什么grade_book = list(gradebook)返回一个空列表,从而使以下操作无效。

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:然后您可以轻松添加新元素并使用.pop() 删除元素:

gradebook.pop('Poetry')
gradebook["Pass"] = "85"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM