📜  Python len()

📅  最后修改于: 2020-09-20 04:15:33             🧑  作者: Mango

len() 函数返回一个对象中的项目数(长度)。

len()的语法为:

len(s)

len()参数

s-序列(字符串,字节,元组,列表或范围)或集合(字典,集合或冻结集合)

从len()返回值

len() 函数返回一个对象的项数。

未能传递参数或传递无效参数将引发TypeError异常。

示例1:len()如何与元组,列表和范围一起使用?

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

访问这些页面以了解有关以下内容的更多信息:

  1. Python列表
  2. Python元组
  3. Python range()方法

示例2:len()如何处理字符串和字节?

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

访问这些页面以了解有关以下内容的更多信息:

  1. Python字符串
  2. Python bytes()方法

示例3:len()如何与字典和集合一起使用?

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

访问这些页面以了解有关以下内容的更多信息:

  1. Python字典
  2. Python集
  3. Python Frozenset()

在内部, len()调用对象的__len__方法。您可以将len()视为:

def len(s):
    return s.__len__()

因此,您可以为对象分配自定义长度(如有必要)

示例4: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