列表是Python编程语言中一种流行的类型。列表包含不同类型的项,如字符串、整数、浮点、列表、字典等。列表的大小等于列表项的计数。但是这个大小与项目计数有关,而不是与内存使用大小有关。这个 长度() 方法由Python2和Python3提供,具有相似的语法和用法。
null
len()方法
Python提供了 len()
方法,其中列表可以作为参数提供,列表的大小或项计数将作为整数返回。len()方法是默认提供的内置方法,不需要导入任何额外的模块。
mylist = [ 1 , 2 , 3 , 4 , 5 ]print("Size of the list is",len(mylist))# Output# Size of the list is 5mylist = [ "a" , "b" , "c" , 1 ,2 , 3 ]print("Size of the list is",len(mylist))# Output# Size of the list is 6mylist = [ "a" , "b" , "c" , [ 1 ,2 , 3 ] ]print("Size of the list is",len(mylist))# Output# Size of the list is 4
获取列表中行的长度
好吧,你已经学会了如何找到一个列表长度。但是你怎么能在列表中找到列表的长度呢?可以向len()方法提供列表列表,该方法将返回元素计数。在下面的示例中,我们将为len()方法提供mylist第3个元素,它也是一个列表。输出为3。
mylist = [ "a" , "b" , "c" , [ 1 ,2 , 3 ] ]print("Size of the list is",len(mylist[3]))# Output# Size of the list is 3
查找列表切片大小
列表是一种动态类型,其中可以返回列表的某些部分,并且可以使用len()方法返回其大小。返回列表的某些部分或某些列表项称为列表切片。下面我们将通过使用len()方法提供开始或结束索引和计数项来返回一些列表项。
mylist = [ "a" , "b" , "c" , [ 1 ,2 , 3 ] ]
print("Size of the list is",len(mylist[1:]))
print("Size of the list is",len(mylist[:3]))
print("Size of the list is",len(mylist[2:]))
# Output
# Size of the list is 3# Size of the list is 4# Size of the list is 2
使用lengthu hint()方法
Python提供了operator模块,该模块具有 长度提示() 方法,以计算所提供的iterable对象的元素总数。由于list是一个iterable对象,因此可以将list提供给lengthu hint()方法以返回list的大小。但是 演出 长度的u hint()小于len()方法。如果性能很重要,请使用len()方法。
import operatormylist = [ "a" , "b" , "c" , [ 1 ,2 , 3 ] ]
print("Size of the list is",operator.length_hint(mylist))
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END