博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
len函数python_Python len()函数
阅读量:2541 次
发布时间:2019-05-11

本文共 1976 字,大约阅读时间需要 6 分钟。

len函数python

Python len() function returns the length of the object. Generally, len() function is used with sequences (string, ) and collections (, ) to get the number of items.

Python len()函数返回对象的长度。 通常,len()函数与序列(字符串, )和集合( , )一起使用以获取项数。

Python len()函数 (Python len() function)

Python len() function returns the length of the object. This function internally calls __len__() function of the object. So we can use len() function with any object that defines __len__() function.

Python len()函数返回对象的长度。 此函数在内部调用对象的__len __()函数。 因此,我们可以将len()函数与任何定义__len __()函数的对象一起使用。

Let’s look at some examples of using len() function with built-in sequences and collection objects.

让我们看一些将len()函数与内置序列和集合对象一起使用的示例。

# len with sequenceprint('string length =', len('abc'))  # stringprint('tuple length =', len((1, 2, 3)))  # tupleprint('list length =', len([1, 2, 3, 4]))  # listprint('bytes length =', len(bytes('abc', 'utf-8')))  # bytesprint('range length =', len(range(10, 20, 2)))  # range# len with collectionsprint('dict length =', len({"a": 1, "b": 2}))  # dictprint('set length =', len(set([1, 2, 3, 3])))  # setprint('frozenset length =', len(frozenset([1, 2, 2, 3])))  # frozenset

Output:

输出:

string length = 3tuple length = 3list length = 4bytes length = 3range length = 5dict length = 2set length = 3frozenset length = 3

Python len()对象 (Python len() Object)

Let’s define a custom class with __len__() function and call len() function with it’s object as argument.

让我们使用__len __()函数定义一个自定义类,并以其对象作为参数调用len()函数。

class Employee:    name = ''    def __init__(self, n):        self.name = n    def __len__(self):        return len(self.name)e = Employee('Pankaj')print('employee object length =', len(e))

Output:

输出:

employee object length = 6

If we remove __len__() function from Employee object, we will get the following exception.

如果我们从Employee对象中删除__len __()函数,我们将得到以下异常。

TypeError: object of type 'Employee' has no len()
. 检出完整的python脚本和更多Python示例。

Reference:

参考:

翻译自:

len函数python

转载地址:http://gtmzd.baihongyu.com/

你可能感兴趣的文章
oracle 查询表的定义语句
查看>>
Android 笔记之 Android 系统架构
查看>>
状压dp终极篇(状态转移的思想)
查看>>
AtCoder Grand Contest 031 B - Reversi
查看>>
完整成功配置wamp server小记
查看>>
build.gradle添加Oracle jdbc6 链接
查看>>
影响系统性能的20个瓶颈--转自开源中国
查看>>
根据ISBN获取豆瓣API提供的图书信息
查看>>
【转】Python中*args和**kwargs的区别
查看>>
git命令简单使用
查看>>
CODEFORCES 125E MST Company 巧用Kruskal算法
查看>>
C++标准库分析总结(三)——<迭代器设计原则>
查看>>
Ibatis 配置问题
查看>>
Notability 3.1 for Mac 中文共享版 – 好用的文本笔记工具
查看>>
HDU 2089 数位dp入门
查看>>
How do I resolve the CodeSign error: CSSMERR_TP_NOT_TRUSTED?
查看>>
linux下添加定时任务
查看>>
python的第三篇--安装Ubuntu、pycharm
查看>>
LeetCode 1092. Shortest Common Supersequence
查看>>
《区块链技术与应用》北京大学肖臻老师公开课 笔记
查看>>