Python中l(wèi)en()函數(shù)用法使用示例
本文圍繞 Python 中的len()函數(shù)展開詳細(xì)介紹,內(nèi)容涵蓋以下方面:
len()函數(shù)基礎(chǔ):
- len()是 Python的內(nèi)置函數(shù),用于返回對象包含的項目數(shù)量,可作用于多種內(nèi)置數(shù)據(jù)類型(如字符串、列表、元組、字典、集合等)以及部分第三方類型(如 NumPy數(shù)組、pandas 的 DataFrame)。
- 對于內(nèi)置類型使用len()較直接,對于自定義類可通過實現(xiàn).len()方法擴展其對len()的支持,且len()函數(shù)大多情況下以 O(1) 時間復(fù)雜度運行,它通過訪問對象的長度屬性獲取結(jié)果。
- 像整數(shù)、浮點數(shù)、布爾值、復(fù)數(shù)等數(shù)據(jù)類型不能作為len()的參數(shù),使用不適用的數(shù)據(jù)類型做參數(shù)會引發(fā)TypeError,同時迭代器和生成器也不能直接用于len()。
不同內(nèi)置數(shù)據(jù)類型中的使用示例:
- 內(nèi)置序列:像字符串、列表、元組、范圍(range)對象等內(nèi)置序列都能用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
- 內(nèi)置集合:通過集合可獲取列表等序列中唯一元素的數(shù)量,字典作為參數(shù)時,len()返回其鍵值對的數(shù)量,空字典和空集合作參數(shù)時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語句結(jié)合len()判斷用戶輸入的用戶名長度是否在指定范圍內(nèi)。
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")
- 基于對象長度結(jié)束循環(huán):比如收集一定數(shù)量的有效用戶名,利用len()判斷列表長度決定循環(huán)是否繼續(xù),也可用于判斷序列是否為空,不過有時使用序列自身的真假性判斷會更 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)
- 查找序列最后一項的索引:生成隨機數(shù)序列并在滿足一定條件后獲取最后一個元素的索引,雖可通過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()計算列表長度找到中點索引來分割列表,若列表元素個數(shù)為奇數(shù),分割結(jié)果兩部分長度會不同。
>>> 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 后,可創(chuàng)建不同維度的數(shù)組,對于二維及多維數(shù)組,len()返回第一維度的大?。ㄈ缍S數(shù)組返回行數(shù)),可通過.shape屬性獲取數(shù)組各維度大小以及用.ndim獲取維度數(shù)量。
>>> 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 后,可從字典創(chuàng)建 DataFrame,len()返回 DataFrame 的行數(shù),其也有.shape屬性體現(xiàn)行列情況。
>>> 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)
- 用戶自定義類中的使用:定義類時可通過實現(xiàn).len()方法自定義對象的長度含義,以使得該類對象能作為len()的參數(shù),同時.len()方法返回的必須是非負(fù)整數(shù)。
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
計算列表的元素個數(shù):
>>> l = ['h','e','l','l','o'] >>> len(l) 5
計算字典的總長度(即鍵值對總數(shù)):
>>> d = {'num':123,'name':"doiido"}
>>> len(d)
2計算元組元素個數(shù):
>>> t = ('G','o','o','d')
>>> len(t)
4總結(jié)
到此這篇關(guān)于Python中l(wèi)en()函數(shù)用法使用示例的文章就介紹到這了,更多相關(guān)Python len()函數(shù)用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python結(jié)合JSON實現(xiàn)動態(tài)按鈕管理程序
這篇文章主要為大家詳細(xì)介紹了如何使用Python的wxPython庫結(jié)合JSON配置文件,開發(fā)一個支持動態(tài)按鈕創(chuàng)建,文件執(zhí)行和配置管理的桌面應(yīng)用程序,感興趣的可以了解下2025-04-04
Python自定義函數(shù)定義,參數(shù),調(diào)用代碼解析
這篇文章主要介紹了Python自定義函數(shù)定義,參數(shù),調(diào)用代碼解析,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12
100行Python代碼實現(xiàn)每天不同時間段定時給女友發(fā)消息
這篇文章主要介紹了100行Python代碼,每天不同時間段定時給女友發(fā)消息,本文給出了實現(xiàn)思路,代碼簡單易懂非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09
Python開發(fā)中OpenCV視頻流的多線程處理方式詳解
在做視覺類項目中,常常需要在Python環(huán)境下使用OpenCV讀取本地的還是網(wǎng)絡(luò)攝像頭的視頻流,之后再調(diào)入各種模型,所以本文我們就來聊聊OpenCV視頻流的多線程處理方式吧2025-05-05
python創(chuàng)建學(xué)生成績管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python創(chuàng)建學(xué)生成績管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11
pytorch torch.gather函數(shù)的使用
torch.gather 是 PyTorch 中用于在指定維度上通過索引從源張量中提取元素的函數(shù),它需要輸入張量、維度索引和索引張量,示例代碼展示了如何使用 torch.gather 從輸入張量中按索引提取元素,返回的結(jié)果張量形狀與索引張量相同2024-09-09
yolov5調(diào)用usb攝像頭及本地攝像頭的方法實例
YOLOV5模型從發(fā)布到現(xiàn)在都是炙手可熱的目標(biāo)檢測模型,被廣泛運用于各大場景之中,下面這篇文章主要給大家介紹了關(guān)于yolov5調(diào)用usb攝像頭及本地攝像頭的相關(guān)資料,需要的朋友可以參考下2022-03-03

