跳至主要内容

Python 列表大小:在 Python 中查找列表长度的 8 种方法

比较在 Python 中查找列表长度的 8 种不同方法。
· 8分钟 阅读

使用 AI 探索

Python 列表是用于存储和操作项目集合的基础数据结构。它们灵活易用,几乎适用于从数据分析到 Web 开发的各种编程任务。鉴于其广泛使用,一个常见需求就是确定列表的大小。虽然众所周知可以使用 len() 函数,但凭借 Python 丰富的语法和库支持,还有多种实现途径,每种都有各自的细微差别与应用场景。本文将探讨其中八种方法,并分析其原理与效率。

为什么 Python 列表很重要?

Python 中的列表是可动态调整大小的数组,能容纳多种数据类型,是存储与处理数据的多面手。它们便于执行迭代、切片等操作,并提供诸如 append()、remove()、sort() 等内置方法以进行丰富的操作。您可以在本教程中进一步了解列表操作。

如何在 Python 中定义列表

在本教程中,我们将使用一个简单的列表演示每种方法。考虑如下定义的列表 my_list:

# Define a sample list to be used throughout the tutorial
my_list = ["I", "Love", "Learning", "Python"]

这个列表虽简单,却非常适合用来演示确定长度的各种技巧。

查找 Python 列表大小的 8 种方法

1. 使用 len() 函数获取列表大小

len() 函数是确定列表大小最直接的方法。不仅简洁,而且高效,是大多数场景的首选。

# Use len() to find the size of the list
length = len(my_list)
print(length)  # Output: 4

2. 使用 for 循环获取列表大小

这种常被称为“朴素方法”的做法,是通过初始化一个计数器,并在遍历列表的 for 循环中对每个元素递增计数。您可以在本教程中进一步了解 for 循环和其他类型的循环。

# Naive method using a for loop to count the list's size
counter = 0
for item in my_list:
    counter += 1
print(counter)  # Output: 4

3. 使用列表推导式获取列表大小

Python 的列表推导式提供了简洁的列表操作语法。这里我们结合 sum() 函数来计数元素个数。

# Using list comprehension to count the list's size
length = sum([1 for item in my_list])
print(length)  # Output: 4

4. 使用 reduce() 获取列表大小

reduce() 功能更进阶也更强大。它会从左到右将一个二元函数依次作用于序列元素,从而将序列归约为一个值。针对我们的目标,可以用它来统计列表中的元素数量。

为便于理解,我们将其分解为两步:

  1. 定义一个简单函数:先定义一个接收两个参数的函数:当前计数(记为 count_so_far)和列表中的某个元素(命名为 _,表示我们并不实际使用它)。
  2. 使用 reduce():然后用 reduce() 将该函数应用到列表的每个元素上,实现逐个计数。
# Import the reduce function from the functools module
from functools import reduce

# Define a simple function to use with reduce
def update_count(count_so_far, _):
    """Increases the count by 1. The second parameter is not used."""
    return count_so_far + 1

# Use reduce to count the items in the list
# We start counting from 0, which is why we have '0' at the end
list_length = reduce(update_count, my_list, 0)

# Print out the result
print(list_length)  # Output will be 4

5. 使用 iter() 和 next() 获取列表大小

要理解如何用 iter() 和 next() 统计列表元素,需要先了解迭代器。迭代器是 Python 中按顺序逐个访问列表元素的对象。iter() 可将列表转换为迭代器,next() 则用于取下一个元素。

步骤如下:

  1. 创建迭代器:使用 iter() 将列表转换为迭代器,以便逐个访问。
  2. 用循环计数:设置一个循环,直到没有更多元素为止。在循环中用 next() 取下一个元素,每成功取到一个元素就将计数加 1。
  3. 处理列表末尾:当到达列表末尾,next() 会触发 StopIteration 异常,表明没有更多元素。我们在 try/except 中捕获该异常并停止计数。

以下是带注释的简化代码,帮助理解每一步:

# Step 1: Turn the list into an iterator
list_iterator = iter(my_list)

# Initialize a counter to keep track of the number of items
count = 0

# Step 2: Loop through the list using the iterator
while True:
    try:
        # Use next() to get the next item from the iterator
        next(list_iterator)
        
        # If next() was successful, increase the count
        count += 1
    except StopIteration:
        # Step 3: If we reach the end of the list, break out of the loop
        break

# Print out the total count of items in the list
print(count)  # Output will be 4

6. 使用 enumerate() 获取列表大小

enumerate() 会为可迭代对象添加计数器,并返回一个enumerate 对象。它常用于循环中同时获得索引和值。尽管 enumerate() 并非常用来获取列表大小,但我们可以借此展示 Python 的灵活性。

# Step 1: Enumerate the list and convert it to a list of tuples (index, element)
enumerated_list = list(enumerate(my_list))

# Step 2: Extract the last tuple (which contains the last index and the last element)
last_tuple = enumerated_list[-1]

# Step 3: The size of the list is the last index plus 1 (because of zero-based indexing)
list_size = last_tuple[0] + 1

# Print out the size of the list
print(list_size)  # Output will be 4

7. 使用 NumPy 获取列表大小

NumPy 是 Python 中功能强大的科学计算库,支持大型多维数组与矩阵,并提供丰富的数学函数来处理这些数组。对数值数据进行处理时,NumPy 提供了高效的存储与运算能力,因而不可或缺。要用 NumPy 获取 Python 列表的大小,我们可以使用 .size 属性,如下所示。

# Import the NumPy library
import numpy as np

# Step 1: Convert the list into a NumPy array
my_array = np.array(my_list)

# Step 2: Use the 'size' attribute of the NumPy array to find its size
array_size = my_array.size

# Print out the size of the array (which is the same as the length of the list)
print(array_size)  # Output will be 4

8. 使用 map() 和 sum() 获取列表大小

与列表推导式类似,此方法用 map() 将一个对每个元素都返回 1 的函数作用于列表,再借助 sum() 聚合这些值以统计元素个数。该方法需要您熟悉 Python 的 lambda 函数。想要快速入门,请查看这篇Python lambda 教程。

# Using map() and sum() to count the list's size
length = sum(map(lambda x: 1, my_list))
print(length)  # Output: 4

比较不同 Python 列表大小方法的性能

了解这八种方法是一回事,挑选最佳方法是另一回事。为比较上述方法的性能,我们将使用 Python 的 timeit 模块来对小段代码进行计时,从而直观了解各方法在执行速度上的差异。请注意,执行时间可能因您的机器或运行环境而异。

实验设置

为便于操作,我们先定义列表以及各方法对应的函数。即使您不熟悉函数也没关系,我们只是将不同方法系统化,方便对比。

import timeit
from functools import reduce
import numpy as np

# Define the list
my_list = ["I", "Love", "Learning", "Python"] * 100  # Increased size for better statistical signifcance

# Method 1: Using len()
def method_len():
    return len(my_list)

# Method 2: Looping through the list
def method_loop():
    counter = 0
    for _ in my_list:
        counter += 1
    return counter

# Method 3: Using a list comprehension
def method_list_comprehension():
    return sum([1 for _ in my_list])

# Method 4: Using reduce()
def method_reduce():
    return reduce(lambda acc, _: acc + 1, my_list, 0)

# Method 5: Using iter() and next()
def method_iter_next():
    iterator = iter(my_list)
    counter = 0
    while True:
        try:
            next(iterator)
            counter += 1
        except StopIteration:
            break
    return counter

# Method 6: Using enumerate()
def method_enumerate():
    return max(enumerate(my_list, 1))[0]

# Method 7: Using numpy
def method_numpy():
    np_array = np.array(my_list)
    return np_array.size

# Method 8: Using map() and sum()
def method_map_sum():
    return sum(map(lambda _: 1, my_list))

为每种方法计时

接下来,我们使用 timeit.timeit() 按既定顺序为每个函数计时:

# List to hold method names and their execution times
timing_results = []

methods = [method_len, method_loop, method_list_comprehension, method_reduce, 
           method_iter_next, method_enumerate, method_numpy, method_map_sum]

# Time each method
for method in methods:
 # Execute the operation 100000 times for better statistical significance  
    time_taken = timeit.timeit(method, number=100000)
    timing_results.append((method.__name__, time_taken))

# Sort results by time taken for better readability
timing_results.sort(key=lambda x: x[1])

# Print the timing results
for method_name, time_taken in timing_results:
    print(f"{method_name}: {time_taken:.5f} seconds")

在 DataLab 中运行后,我们得到如下结果:

方法

耗时

len() 方法

0.03410 seconds

列表推导式方法

1.50325 seconds

for 循环方法

1.93764 seconds

enumerate() 方法

2.26446 seconds

map() 与 sum() 方法

2.41315 seconds

iter() 与 next() 方法

3.08434 seconds

reduce() 方法

4.41239 seconds

numpy 方法

10.61716 seconds

结论

总的来说,本文探讨的多种在 Python 中获取列表大小的方法,不仅展示了 Python 语言的多样性与强大能力,也强调了理解不同方法效率与适用场景的重要性。

对于初学者而言,建议从最直接高效的方法入手,例如内置的 len(),它在性能与可读性方面都表现出色。若想进一步学习列表相关内容,请参考以下资源:

Adel Nehme

作者

Adel Nehme

Adel 是一位数据科学教育者、演讲者,以及 DataCamp 的媒体副总裁。他推出了多门关于数据分析、机器学习和数据工程的课程与直播培训,热衷于在组织内推广数据技能与数据素养,并关注技术与社会的交汇。他拥有数据科学与商业分析硕士学位。闲暇时,您常能发现他陪他的猫 Louis 一起玩耍。

主题