📅  最后修改于: 2020-09-20 04:15:33             🧑  作者: Mango
len()
的语法为:
len(s)
s-序列(字符串,字节,元组,列表或范围)或集合(字典,集合或冻结集合)
len()
函数返回一个对象的项数。
未能传递参数或传递无效参数将引发TypeError
异常。
testList = []
print(testList, 'length is', len(testList))
testList = [1, 2, 3]
print(testList, 'length is', len(testList))
testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple))
testRange = range(1, 10)
print('Length of', testRange, 'is', len(testRange))
输出
[] length is 0
[1, 2, 3] length is 3
(1, 2, 3) length is 3
Length of range(1, 10) is 9
访问这些页面以了解有关以下内容的更多信息:
testString = ''
print('Length of', testString, 'is', len(testString))
testString = 'Python'
print('Length of', testString, 'is', len(testString))
# byte object
testByte = b'Python'
print('Length of', testByte, 'is', len(testByte))
testList = [1, 2, 3]
# converting to bytes object
testByte = bytes(testList)
print('Length of', testByte, 'is', len(testByte))
输出
Length of is 0
Length of Python is 6
Length of b'Python' is 6
Length of b'\x01\x02\x03' is 3
访问这些页面以了解有关以下内容的更多信息:
testSet = {1, 2, 3}
print(testSet, 'length is', len(testSet))
# Empty Set
testSet = set()
print(testSet, 'length is', len(testSet))
testDict = {1: 'one', 2: 'two'}
print(testDict, 'length is', len(testDict))
testDict = {}
print(testDict, 'length is', len(testDict))
testSet = {1, 2}
# frozenSet
frozenTestSet = frozenset(testSet)
print(frozenTestSet, 'length is', len(frozenTestSet))
输出
{1, 2, 3} length is 3
set() length is 0
{1: 'one', 2: 'two'} length is 2
{} length is 0
frozenset({1, 2}) length is 2
访问这些页面以了解有关以下内容的更多信息:
在内部, len()
调用对象的__len__
方法。您可以将len()
视为:
def len(s):
return s.__len__()
因此,您可以为对象分配自定义长度(如有必要)
class Session:
def __init__(self, number = 0):
self.number = number
def __len__(self):
return self.number
# default length is 0
s1 = Session()
print(len(s1))
# giving custom length
s2 = Session(6)
print(len(s2))
输出
0
6