最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

本文圍繞 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()較直接,對于自定義類可通過實(shí)現(xiàn).len()方法擴(kuò)展其對len()的支持,且len()函數(shù)大多情況下以 O(1) 時間復(fù)雜度運(yùn)行,它通過訪問對象的長度屬性獲取結(jié)果。
  • 像整數(shù)、浮點(diǎn)數(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)
  • 查找序列最后一項的索引:生成隨機(jī)數(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()計算列表長度找到中點(diǎn)索引來分割列表,若列表元素個數(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)
  • 用戶自定義類中的使用:定義類時可通過實(shí)現(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)

附:實(shí)例

計算字符串的長度:

>>> 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)文章

最新評論

河东区| 津南区| 四子王旗| 临安市| 哈密市| 和林格尔县| 东方市| 肇庆市| 博客| 于都县| 天等县| 贵港市| 赤城县| 南部县| 凤阳县| 周宁县| 油尖旺区| 高唐县| 汤阴县| 潮安县| 宁蒗| 中山市| 锦屏县| 富锦市| 澄迈县| 杭州市| 仲巴县| 舟山市| 潼南县| 长岭县| 富源县| 泊头市| 贵溪市| 平谷区| 西华县| 杂多县| 江西省| 肥西县| 呈贡县| 泊头市| 合作市|