如何在Python中查找列表的长度

介绍

在Python中,有几种技巧可以用来找到列表的长度。列表的长度就是列表中元素的个数。本文介绍了三种方法来找到列表的长度,然而,len()方法通常是获取列表长度的最佳途径,因为它是最高效的。由于列表是一个对象,列表的大小已经存储在内存中以便快速检索。

使用len()方法来获取列表的长度

你可以使用内置的len()方法来找到列表的长度。

len()方法接受一个序列或一个集合作为参数,并返回序列或集合中元素的数量。

len()的语法是:

len(s)

以下示例提供了一个列表,并使用len()方法获取列表的长度。

inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript']
size = len(inp_lst)
print(size)

输出为:

Output

4

寻找列表长度的其他方法

虽然通常使用len()方法是获取列表长度的最佳方法,因为它效率最高,但在Python中还有其他几种方法可以获取列表的长度。

使用length_hint()方法获取列表的长度

Python的操作符模块中有一个length_hint()方法,用于估计给定可迭代对象的长度。如果长度已知,length_hint()方法将返回实际的长度。否则,length_hint()方法将返回一个估计的长度。对于列表,长度始终是已知的,所以通常只需要使用len()方法。

length_hint()的语法是:

length_hint(object)

下面的示例提供了一个列表,并使用length_hint()方法获取列表的长度

from operator import length_hint 
inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript']
size = length_hint(inp_lst)
print(size)

输出是:

Output

4

使用一个for循环来获取一个列表的长度

本节提供一种较不实用但仍具有信息量的方法来计算不带特殊方法的列表长度。使用for循环来获取列表长度也被称为朴素方法,可以适用于几乎任何编程语言。

使用for循环获取列表长度的基本步骤是:

  • Declare a counter variable and initialize it to zero.
    counter = 0
  • Use a for loop to traverse through all the data elements and, after encountering each element, increment the counter variable by 1.
    for item in list:
    counter += 1
  • The length of the array is stored in the counter variable and the variable represents the number of elements in the list. The variable can be used in other code or output.
    print(counter)

以下示例演示如何获取列表的长度。

inp_lst = ['Python', 'Java', 'Ruby', 'JavaScript']
size = 0
for x in inp_lst:
    size += 1
print(size)

结果是:

Output

4

结论

在这篇文章中,您学习到了一些在Python中找到列表长度的不同方法。继续学习更多的Python教程吧。

广告
将在 10 秒后关闭
bannerAds