欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中l(wèi)en()函數(shù)用法使用示例

 更新時間:2025年03月05日 09:21:35   作者:wildgeek  
這篇文章主要介紹了Python中的len()函數(shù),包括其基礎(chǔ)用法、適用范圍、常見使用場景以及在第三方庫(如NumPy和pandas)中的應(yīng)用,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

本文圍繞 Python 中的len()函數(shù)展開詳細介紹,內(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()方法返回的必須是非負整數(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實現(xiàn)粒子群算法詳解

    Python實現(xiàn)粒子群算法詳解

    這篇文章主要介紹了Python實現(xiàn)粒子群算法詳解,粒子群算法,縮寫為PSO(Particle Swarm Optimization),是一種非線性尋優(yōu)算法,其特點是實現(xiàn)簡單、收斂速度快,對多元函數(shù)的局部最優(yōu)有較好的克服能力,需要的朋友可以參考下
    2023-07-07
  • Python實現(xiàn)腳本轉(zhuǎn)換為命令行程序

    Python實現(xiàn)腳本轉(zhuǎn)換為命令行程序

    使用Python中的scaffold和click庫,你可以將一個簡單的實用程序升級為一個成熟的命令行界面工具,本文就來帶你看看具體實現(xiàn)方法,感興趣的可以了解下
    2022-09-09
  • Python常用內(nèi)置函數(shù)和關(guān)鍵字使用詳解

    Python常用內(nèi)置函數(shù)和關(guān)鍵字使用詳解

    在Python中有許許多多的內(nèi)置函數(shù)和關(guān)鍵字,它們是我們?nèi)粘V薪?jīng)??梢允褂玫牡降囊恍┗A(chǔ)的工具,可以方便我們的工作。本文將詳細講解他們的使用方法,需要的可以參考一下
    2022-05-05
  • 深入淺析Python 函數(shù)注解與匿名函數(shù)

    深入淺析Python 函數(shù)注解與匿名函數(shù)

    這篇文章主要介紹了Python 函數(shù)注解與匿名函數(shù)的相關(guān)知識,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-02-02
  • win10 64bit下python NLTK安裝教程

    win10 64bit下python NLTK安裝教程

    這篇文章主要為大家詳細介紹了win10 64bit下python NLTK安裝教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • Python+Pygame實戰(zhàn)之炫舞小游戲的實現(xiàn)

    Python+Pygame實戰(zhàn)之炫舞小游戲的實現(xiàn)

    提到QQ炫舞,可能很多人想到的第一個詞是“青春”?;腥婚g,這個承載了無數(shù)人回憶與時光的游戲品牌,已經(jīng)走到了第十幾個年頭。今天小編就來給大家嘗試做一款簡單的簡陋版的小游戲——《舞動青春*炫舞》,感興趣的可以了解一下
    2022-12-12
  • Python中多返回值的應(yīng)用場景

    Python中多返回值的應(yīng)用場景

    Python 是一種非常靈活的編程語言,它允許函數(shù)返回多個值,本文主要介紹了Python中多返回值的應(yīng)用場景,具有一定的參考價值,感興趣的可以了解一下
    2024-06-06
  • 簡單示例解析python爬蟲IP的使用(小白篇)

    簡單示例解析python爬蟲IP的使用(小白篇)

    這篇文章主要為大家通過簡單示例解析python爬蟲IP的使用介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-06-06
  • Python寫入數(shù)據(jù)到MP3文件中的方法

    Python寫入數(shù)據(jù)到MP3文件中的方法

    這篇文章主要介紹了Python寫入數(shù)據(jù)到MP3文件中的方法,可實現(xiàn)將MP3文件相關(guān)信息寫入MP3文件的功能,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-07-07
  • Python3.0與2.X版本的區(qū)別實例分析

    Python3.0與2.X版本的區(qū)別實例分析

    這篇文章主要介紹了Python3.0與2.X版本的區(qū)別,包含了一些常見的區(qū)別及分析,還有筆者的一些感悟,需要的朋友可以參考下
    2014-08-08

最新評論