最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

Python内置函数len

来源:动视网 责编:小采 时间:2020-11-27 14:28:05
文档

Python内置函数len

Python内置函数len:英文文档:len(s)Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dicti
推荐度:
导读Python内置函数len:英文文档:len(s)Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dicti

英文文档:

len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

说明:

 1. 返回对象的长度,参数可以是序列(比如字符串、字节数组、元组、列表和range对象),或者是集合(比如字典、集合、不可变集合)

>>> len('abcd') # 字符串
>>> len(bytes('abcd','utf-8')) # 字节数组
>>> len((1,2,3,4)) # 元组
>>> len([1,2,3,4]) # 列表
>>> len(range(1,5)) # range对象
>>> len({'a':1,'b':2,'c':3,'d':4}) # 字典
>>> len({'a','b','c','d'}) # 集合
>>> len(frozenset('abcd')) #不可变集合

 2. 如果参数为其它类型,则其必须实现__len__方法,并返回整数,否则报错。

>>> class A:
 def __init__(self,name):
 self.name = name
 def __len__(self):
 return len(self.name)

>>> a = A('')
>>> len(a)
>>> a = A('Aim')
>>> len(a)
>>> class B:
 pass

>>> b = B()
>>> len(b)
Traceback (most recent call last):
 File "", line 1, in 
 len(b)
TypeError: object of type 'B' has no len()
>>> class C:
 def __len__(self):
 return 'len'

>>> c = C()
>>> len(c)
Traceback (most recent call last):
 File "", line 1, in 
 len(c)
TypeError: 'str' object cannot be interpreted as an integer

文档

Python内置函数len

Python内置函数len:英文文档:len(s)Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dicti
推荐度:
标签: 函数 python len
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top