Python len()函数
时间:2020-02-23 14:42:53 来源:igfitidea点击:
Python len()函数返回对象的长度。
通常,len()函数与序列(字符串,元组)和集合(dict,set)一起使用以获取项数。
Python len()函数
Python len()函数返回对象的长度。
此函数在内部调用对象的__len __()
函数。
因此,我们可以将len()函数与定义__len __()
函数的任何对象一起使用。
让我们看一些将len()函数与内置序列和集合对象一起使用的示例。
# len with sequence print('string length =', len('abc')) # string print('tuple length =', len((1, 2, 3))) # tuple print('list length =', len([1, 2, 3, 4])) # list print('bytes length =', len(bytes('abc', 'utf-8'))) # bytes print('range length =', len(range(10, 20, 2))) # range # len with collections print('dict length =', len({"a": 1, "b": 2})) # dict print('set length =', len(set([1, 2, 3, 3]))) # set print('frozenset length =', len(frozenset([1, 2, 2, 3]))) # frozenset
输出:
string length = 3 tuple length = 3 list length = 4 bytes length = 3 range length = 5 dict length = 2 set length = 3 frozenset length = 3
Python len()对象
让我们使用__len __()
函数定义一个自定义类,然后以其对象作为参数调用len()函数。
class Employee: name = '' def __init__(self, n): self.name = n def __len__(self): return len(self.name) e = Employee('hyman') print('employee object length =', len(e))
输出:
employee object length = 6
如果我们从Employee对象中删除__len __()
函数,我们将得到以下异常。
TypeError: object of type 'Employee' has no len()