python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python len()函数用法

Python中len()函数用法使用示例

作者:wildgeek

这篇文章主要介绍了Python中的len()函数,包括其基础用法、适用范围、常见使用场景以及在第三方库(如NumPy和pandas)中的应用,文中通过代码介绍的非常详细,需要的朋友可以参考下

本文围绕 Python 中的len()函数展开详细介绍,内容涵盖以下方面:

len()函数基础:

不同内置数据类型中的使用示例:

>>> 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
>>> 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

常见使用场景举例:

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")
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)
>>> 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]
>>> 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]

第三方库中的使用:

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

计算列表的元素个数:

>>> l = ['h','e','l','l','o']
>>> len(l)
5

计算字典的总长度(即键值对总数):

>>> d = {'num':123,'name':"doiido"}
>>> len(d)
2

计算元组元素个数:

>>> t = ('G','o','o','d')
>>> len(t)
4

总结 

到此这篇关于Python中len()函数用法使用示例的文章就介绍到这了,更多相关Python len()函数用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文