原文:Python List Length – How to Get the Size of a List in Python,作者:Kolade Chris
在 Python 中,你使用列表来存储各种类型的数据,如字符串和数字。
一个列表可以通过它周围的方括号来识别,列表中单个的值用逗号来分隔。
要在 Python 中获取一个列表的长度,可以使用内置的 len()
函数。
除了 len()
函数外,你还可以使用 for
循环和 length_hint()
函数来获得列表的长度。
在这篇文章中,我将向你展示如何用 3 种不同的方法获取列表的长度。
如何在 Python 中用 for 循环获取列表的长度
你可以使用 Python 的原生 for 循环来获得一个列表的长度,因为就像元组和字典一样,列表是可迭代的。
下面的例子告诉你如何使用这个方法来获取 Python 中列表的长度。
demoList = ["Python", 1, "JavaScript", True, "HTML", "CSS", 22]
# 初始化 counter 变量
counter = 0
for item in demoList:
# 递增 counter 变量以获取列表中的每个元素
counter = counter + 1
# 通过将 counter 转换为字符串,将结果打印到控制台,以获得数字
print("The length of the list using the naive method is: " + str(counter))
# Output: The length of the list using the naive method is: 7
如何用 len()
函数获取列表的长度
使用 len()
函数是获取迭代器长度的最常用方法。
这比使用 for
循环更直接。
使用 len()
方法的语法是 len(listName)
。
下面的代码片段显示了如何使用 len()
函数来获取一个列表的长度:
demoList = ["Python", 1, "JavaScript", True, "HTML", "CSS", 22]
sizeOfDemoList = len(demoList)
print("The length of the list using the len() method is: " + str(sizeOfDemoList))
# Output: The length of the list using the len() method is: 7
如何使用 length_hint()
函数获取列表的长度
length_hint()
方法是一种不太为人所知的获取列表和其他迭代表长度的方法。
在 operator 模块中定义 length_hint()
,所以你需要在使用它之前从那里导入它。
使用 len()
方法的语法是 length_hint(listName)
。
下面的例子告诉你如何使用 length_hint()
方法来获取一个列表的长度,从 operator 导入 length_hint()
。
demoList = ["Python", 1, "JavaScript", True, "HTML", "CSS", 22]
sizeOfDemoList = length_hint(demoList)
print("The length of the list using the length_hint() method is: " + str(sizeOfDemoList))
# The length of the list using the length_hint() method is: 7
小结
这篇文章向你展示了如何用 3 种不同的方法获得一个列表的大小:for
循环、len()
函数和 operator 模块的 length_hint()
函数。
你可能想知道在这 3 种方法中应该使用哪一种。
我建议你使用 len()
,因为与 for
循环和 length_hint()
相比,它更简单。
此外,len()
似乎比 for
循环和 length_hint()
都快。
如果你觉得这篇文章对你有帮助,请分享它,以便其他需要它的人也能看到。