使用類操作列表元素(追加、刪除和顯示)的Python程式
當需要使用類來追加、刪除和顯示列表元素時,可以使用面向物件的方法。在此,定義一個類,並定義屬性。在類中定義函式以執行某些操作。建立類的例項,並使用函式透過物件向列表新增元素,從列表中刪除元素以及顯示列表元素。
以下是相同的演示示例:
示例
class list_class(): def __init__(self): self.n=[] def add_val(self,a): return self.n.append(a) def remove_val(self,b): self.n.remove(b) def display_val(self): return (self.n) my_instance = list_class() choice_val = 1 while choice_val!=0: print("0. Exit") print("1. Add elements") print("2. Delete element") print("3. Display list") choice_val=int(input("Enter your choice: ")) if choice_val==1: n=int(input("Enter element to add to the list... ")) my_instance.add_val(n) print("List: ",my_instance.display_val()) elif choice_val==2: n=int(input("Enter number to delete..")) my_instance.remove_val(n) print("List: ",my_instance.display_val()) elif choice_val==3: print("List: ",my_instance.display_val()) elif choice_val==0: print("Exit") else: print("Invalid choice!") print()
輸出
0. Exit 1. Add elements 2. Delete element 3. Display list Enter your choice: 1 Enter element to add to the list... 34 List: [34] 0. Exit 1. Add elements 2. Delete element 3. Display list Enter your choice: 3 List: [34] 0. Exit 1. Add elements 2. Delete element 3. Display list Enter your choice: 2 Enter number to delete..34 List: [] 0. Exit 1. Add elements 2. Delete element 3. Display list Enter your choice: 0 Exit
解釋
- 定義了一個名為“list_class”的類,該類具有諸如“add_val”、“remove_val”和“display_val”之類的函式。
- 這些函式分別用於向列表新增元素,從列表中刪除元素以及顯示列表。建立此類的例項。
- 輸入列表元素並在其上執行操作。
- 在控制檯上顯示相關的訊息和輸出。
廣告