Python中的len()函数用法

本文围绕 Python 中的len()函数展开详细介绍,内容涵盖以下方面:

len()函数基础:

len()是 Python的内置函数,用于返回对象包含的项目数量,可作用于多种内置数据类型(如字符串、列表、元组、字典、集合等)以及部分第三方类型(如 NumPy数组、pandas 的 DataFrame)。对于内置类型使用len()较直接,对于自定义类可通过实现.len()方法扩展其对len()的支持,且len()函数大多情况下以 O(1) 时间复杂度运行,它通过访问对象的长度属性获取结果。像整数、浮点数、布尔值、复数等数据类型不能作为len()的参数,使用不适用的数据类型做参数会引发TypeError,同时迭代器和生成器也不能直接用于len()。

不同内置数据类型中的使用示例:

内置序列:像字符串、列表、元组、范围(range)对象等内置序列都能用len()获取长度,空序列使用len()返回 0。

>>> greeting = "Good Day!"

>>> len(greeting)

9

>>> office_days = ["Tuesday", "Thursday", "Friday"]

>>> len(office_days)

3

>>> london_coordinates = (51.50722, -0.1275)

>>> len(london_coordinates)

2

>>> len("")

0

>>> len([])

0

>>> len(())

0

内置集合:通过集合可获取列表等序列中唯一元素的数量,字典作为参数时,len()返回其键值对的数量,空字典和空集合作参数时len()返回 0。>>> import random

>>> numbers = [random.randint(1, 20) for _ in range(20)]

>>> numbers

[3, 8, 19, 1, 17, 14, 6, 19, 14, 7, 6, 1, 17, 10, 8, 14, 17, 10, 2, 5]

>>> unique_numbers = set(numbers)

>>> unique_numbers

{1, 2, 3, 5, 6, 7, 8, 10, 14, 17, 19}

>>> len(unique_numbers)

11

常见使用场景举例:

验证用户输入长度:用if语句结合len()判断用户输入的用户名长度是否在指定范围内。

username = input("Choose a username: [4-10 characters] ")

if 4 <= len(username) <= 10:

print(f"Thank you. The username {username} is valid")

else:

print("The username must be between 4 and 10 characters long")

基于对象长度结束循环:比如收集一定数量的有效用户名,利用len()判断列表长度决定循环是否继续,也可用于判断序列是否为空,不过有时使用序列自身的真假性判断会更 Pythonic。

usernames = []

print("Enter three options for your username")

while len(usernames) < 3:

username = input("Choose a username: [4-10 characters] ")

if 4 <= len(username) <= 10:

print(f"Thank you. The username {username} is valid")

usernames.append(username)

else:

print("The username must be between 4 and 10 characters long")

print(usernames)

查找序列最后一项的索引:生成随机数序列并在满足一定条件后获取最后一个元素的索引,虽可通过len()计算,但也存在更 Pythonic 的方法,如使用索引 -1 等。

>>> import random

>>> numbers = []

>>> while sum(numbers) <= 21:

... numbers.append(random.randint(1, 10))

...

>>> numbers

[3, 10, 4, 7]

>>> numbers[len(numbers) - 1]

7

>>> numbers[-1] # A more Pythonic way to retrieve the last item

7

>>> numbers.pop(len(numbers) - 1) # You can use numbers.pop(-1) or numbers.pop()

7

>>> numbers

[3, 10, 4]

分割列表为两部分:利用len()计算列表长度找到中点索引来分割列表,若列表元素个数为奇数,分割结果两部分长度会不同。

>>> import random

>>> numbers = [random.randint(1, 10) for _ in range(10)]

>>> numbers

[9, 1, 1, 2, 8, 10, 8, 6, 8, 5]

>>> first_half = numbers[: len(numbers) // 2]

>>> second_half = numbers[len(numbers) // 2 :]

>>> first_half

[9, 1, 1, 2, 8]

>>> second_half

[10, 8, 6, 8, 5]

第三方库中的使用:

NumPy 的ndarray:安装 NumPy 后,可创建不同维度的数组,对于二维及多维数组,len()返回第一维度的大小(如二维数组返回行数),可通过.shape属性获取数组各维度大小以及用.ndim获取维度数量。

>>> import numpy as np

>>> numbers = np.array([4, 7, 9, 23, 10, 6])

>>> type(numbers)

>>> len(numbers)

6

>>> numbers = [

[11, 1, 10, 10, 15],

[14, 9, 16, 4, 4],

[28, 1, 19, 7, 7],

]

>>> numbers_array = np.array(numbers)

>>> numbers_array

array([[11, 1, 10, 10, 15],

[14, 9, 16, 4, 4],

[28, 1, 19, 7, 7])

>>> len(numbers_array)

3

>>> numbers_array.shape

(3, 5)

>>> len(numbers_array.shape)

2

>>> numbers_array.ndim

2

pandas 的DataFrame:安装 pandas 后,可从字典创建 DataFrame,len()返回 DataFrame 的行数,其也有.shape属性体现行列情况。

>>> import pandas as pd

>>> marks = {

"Robert": [60, 75, 90],

"Mary": [78, 55, 87],

"Kate": [47, 96, 85],

"John": [68, 88, 69],

}

>>> marks_df = pd.DataFrame(marks, index=["Physics", "Math", "English"])

>>> marks_df

Robert Mary Kate John

Physics 60 78 47 68

Math 75 55 96 88

English 90 87 85 69

>>> len(marks_df)

3

>>> marks_df.shape

(3, 4)

用户自定义类中的使用:定义类时可通过实现.len()方法自定义对象的长度含义,以使得该类对象能作为len()的参数,同时.len()方法返回的必须是非负整数。

class DataFrame(NDFrame, OpsMixin):

# ...

def __len__(self) -> int:

"""

Returns length of info axis, but here we use the index.

"""

return len(self.index)