此 Python 函数用于清除或删除列表中的所有项,其语法为
list_name.clear()
Python 列表 clear 示例
在此示例中,我们声明了一个字符串列表和一个整数列表。接下来,我们对它们使用 clear 函数来删除所有元素。
a = [10, 20, 30, 40]
Fruits = ['Apple', 'Banana', 'Kiwi', 'Grape']
print("Before : ", a)
a.clear()
print("After : ", a)
print("\nBefore : ", Fruits)
Fruits.clear()
print("After : ", Fruits)
Before : [10, 20, 30, 40]
After : []
Before : ['Apple', 'Banana', 'Kiwi', 'Grape']
After : []
此方法会删除所有现有项。执行此 clear 方法后,它会返回一个空列表。
Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
numbers = [9, 4, -5, 0, 22, -1, 2, 14]
print(Fruits)
print(numbers)
New_Fruits = Fruits.clear()
print("\nNew : ", New_Fruits)
new_numbers = numbers.clear()
print("New Number : ", new_numbers)
['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
[9, 4, -5, 0, 22, -1, 2, 14]
New : None
New Number : None
在此 程序 中,我们允许用户输入其长度。接下来,我们使用 For 循环 来追加这些数字。然后我们使用此方法删除这些项。
intClearList = []
number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
intClearList.append(value)
print("Before Clear() - Items in this List are : ", intClearList)
intClearList.clear()
print("After Clear() - Items in this List are : ", intClearList)

它允许用户输入自己的字符串或单词,然后删除这些项。您也可以将其用于混合和嵌套列表。
str1 = []
number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, number + 1):
value = input("%d Element : " %i)
str1.append(value)
print("Before = ", st1)
str1.clear()
print("After = ", str1)
Please enter the Total Number of Elements: 4
1 Element : Dragon
2 Element : Cherry
3 Element : Kiwi
4 Element : Banana
Before = ['Dragon', 'Cherry', 'Kiwi', 'Banana']
After = []