Python len()

内置函数len()用于返回对象的长度,即对象中的多个元素。这里的对象可以是字符串、数组、列表、元组、字典等。

 **len(object)** # object can be string,sets,tuples,dictionary etc

len()参数:

只接受一个参数。在这种情况下,序列可以是字符串、字节、元组、列表或范围,集合可以是字典、集合或冻结集合。

参数 描述 必需/可选
目标 序列或集合 需要

len()返回值

如果缺少参数或传递了无效的参数,将引发类型错误异常。

| 投入 | 返回值 | | 一个对象 | 对象的长度(整数值) |

Python 中len()方法的示例

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

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

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

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

本文链接:https://my.lmcjl.com/post/6345.html

展开阅读全文

4 评论

留下您的评论.