Python中的len()函数用法
本文围绕 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)
作者:wildgeek