python的len()函数比较常用的用法和功能实例

python的len()函数

len()函数是python的内置函数之一,也是python编程实战过程中经常用到的内置函数之一,用来查询返回len()函数参数(一般为可迭代的对象)的长度大小的值,注意,是长度,即个数,而不是字节数,二者要区别开来。这与javascript、java的.length和c/c++中的length()函数十分相似,而且一般常用于for循环。

len()函数的语法结构

len( object ) -> int;

  • object一般为可迭代的python对象,如list列表、tuple元组、dict字典、set集合、str字符串、range类型等等;
  • “->”符号指定len()函数的返回值是一个int类型的数据;

len()函数实例代码

len()函数可以用来直接查询python对象的长度,也可以用来进行for循环,而且这也是len()在python编程中常用的用法之一:

>>> len(range(10))
10
>>> type(range(10))

>>> len([1,2])
2
>>> len(('a','b'))
2
>>> len('')
0
>>> len({'a':1,'b':2,'c':3})
3
>>> a = list(range(3))
>>> a
[0, 1, 2]
>>> for i in range(len(a)):
...     print(a[i])
... 
0
1
2
>>> len(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> len(True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'bool' has no len()

代码解析

如上代码,当len()函数的参数为int或bool之类的非可迭代对象的时候,python程序会抛出TypeError提示。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.