要在Python中查找列表中的元素总数,我们使用len()方法,它是一个内置方法,它接受一个参数(此列表)并返回元素总数。
语法:
len(list_object/list_elements)
注意:作为参数,可以传递列表对象或直接列表([elemen1,element2,...])。
范例1:
# 申报清单 list1 = [10, 20, 30, 40, 50] list2 = ["Hello", "NHOOO"] # 打印清单及其长度 print("list1: ", list1) print("list2: ", list2) print("len(list1): ", len(list1)) print("len(list2): ", len(list2)) # 将直接列表元素传递给函数 print("Here, elements are: ", len([10,20,30,40,50]))
输出
list1: [10, 20, 30, 40, 50] list2: ['Hello', 'NHOOO'] len(list1): 5 len(list2): 2 Here, elements are: 5
范例2:
# 申报清单 list1 = [10, 20, 30, 40, 50] list2 = ["Hello", "NHOOO"] list3 = ["Hello", 10, 20, "NHOOO"] # 找出清单的长度 # 在附加元素之前 print("Before appending...") print("list1: ", list1) print("list2: ", list2) print("list3: ", list3) print("Elements in list1: ", len(list1)) print("Elements in list2: ", len(list2)) print("Elements in list3: ", len(list3)) # 附加元素 list1.append(60) list1.append(70) list2.append(".com") list3.append(30) # 找出清单的长度 # 附加元素之后 print() # 打印新行 print("After appending...") print("list1: ", list1) print("list2: ", list2) print("list3: ", list3) print("Elements in list1: ", len(list1)) print("Elements in list2: ", len(list2)) print("Elements in list3: ", len(list3))
输出
Before appending... list1: [10, 20, 30, 40, 50] list2: ['Hello', 'NHOOO'] list3: ['Hello', 10, 20, 'NHOOO'] Elements in list1: 5 Elements in list2: 2 Elements in list3: 4 After appending... list1: [10, 20, 30, 40, 50, 60, 70] list2: ['Hello', 'NHOOO', '.com'] list3: ['Hello', 10, 20, 'NHOOO', 30] Elements in list1: 7 Elements in list2: 3 Elements in list3: 5
要计算给定元素的出现次数–我们使用method,它接受要查找其出现次数的参数并返回其出现次数。List.count()
例子:
# 申报清单 list1 = [10, 20, 30, 40, 50, 10, 60, 10] list2 = ["Hello", "NHOOO"] list3 = ["Hello", 10, 20, "NHOOO"] # 打印列表及其元素 print("list1: ", list1) print("list2: ", list2) print("list3: ", list3) print("Elements in list1: ", len(list1)) print("Elements in list2: ", len(list2)) print("Elements in list3: ", len(list3)) # 打印元素的出现 print("occurrences of 10 in list1: ", list1.count(10)) print("occurrences of 60 in list1: ", list1.count(60)) print("occurrences of 70 in list1: ", list1.count(70)) print("occurrences of \"Hello\" in list2: ", list2.count("Hello")) print("occurrences of \"World\" in list2: ", list2.count("World")) print("occurrences of \"NHOOO\" in list3: ", list3.count("NHOOO"))
输出
list1: [10, 20, 30, 40, 50, 10, 60, 10] list2: ['Hello', 'NHOOO'] list3: ['Hello', 10, 20, 'NHOOO'] Elements in list1: 8 Elements in list2: 2 Elements in list3: 4 occurrences of 10 in list1: 3 occurrences of 60 in list1: 1 occurrences of 70 in list1: 0 occurrences of "Hello" in list2: 1 occurrences of "World" in list2: 0 occurrences of "NHOOO" in list3: 1