本文共 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() 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
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()
Reference:
参考:
翻译自:
len函数python
转载地址:http://gtmzd.baihongyu.com/