没有合适的资源?快使用搜索试试~ 我知道了~
Python通过len函数返回对象长度
5星 · 超过95%的资源 3 下载量 87 浏览量
2020-12-16
21:08:56
上传
评论
收藏 34KB PDF 举报
温馨提示
试读
1页
英文文档: 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对象),或者是集合(比如字典、集合、不可变集合) >>>
资源详情
资源评论
资源推荐
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 dictionary, set, or frozen set).
返回对象的长度
说明:
1. 返回对象的长度,参数可以是序列(比如字符串、字节数组、元组、列表和range对象),或者是集合(比如字典、集合、
不可变集合)
>>> len('abcd') # 字符串
4
>>> len(bytes('abcd','utf-8')) # 字节数组
4
>>> len((1,2,3,4)) # 元组
4
>>> len([1,2,3,4]) # 列表
4
>>> len(range(1,5)) # range对象
4
>>> len({'a':1,'b':2,'c':3,'d':4}) # 字典
4
>>> len({'a','b','c','d'}) # 集合
4
>>> len(frozenset('abcd')) #不可变集合
4
2. 如果参数为其它类型,则其必须实现__len__方法,并返回整数,否则报错。
>>> class A:
def __init__(self,name):
self.name = name
def __len__(self):
return len(self.name)
>>> a = A('')
>>> len(a)
0
>>> a = A('Aim')
>>> len(a)
3
>>> class B:
pass
>>> b = B()
>>> len(b)
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
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 "<pyshell#71>", line 1, in <module>
len(c)
TypeError: 'str' object cannot be interpreted as an integer
您可能感兴趣的文章您可能感兴趣的文章:Python中Selenium模块的使用详解python 服务器运行代码报错ModuleNotFoundError的解决办法Python
selenium环境搭建实现过程解析Python Selenium自动化获取页面信息的方法Python3+selenium配置常见报错解决方案Python
Selenium实现无可视化界面过程解析Python selenium爬取微信公众号文章代码详解
weixin_38631773
- 粉丝: 5
- 资源: 963
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论10