Python中len()函数用法使用示例
更新时间:2025年03月05日 09:21:35 作者:wildgeek
这篇文章主要介绍了Python中的len()函数,包括其基础用法、适用范围、常见使用场景以及在第三方库(如NumPy和pandas)中的应用,文中通过代码介绍的非常详细,需要的朋友可以参考下
本文围绕 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) <class 'numpy.ndarray'> >>> 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)
附:实例
计算字符串的长度:
>>> s = "hello good boy doiido" >>> len(s) 21
计算列表的元素个数:
>>> l = ['h','e','l','l','o'] >>> len(l) 5
计算字典的总长度(即键值对总数):
>>> d = {'num':123,'name':"doiido"} >>> len(d) 2
计算元组元素个数:
>>> t = ('G','o','o','d') >>> len(t) 4
总结
到此这篇关于Python中len()函数用法使用示例的文章就介绍到这了,更多相关Python len()函数用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
最新评论