- Host World
- Компанія
- Блог
- Інструменти програмування
- How to find the length of a list in Python?
Як знайти довжину списку в Python?
-
3 min читати
-
242
У цьому прикладі ми створюємо список даних про населення та обчислюємо його довжину:
population_data = [8370000, 3980000, 2790000, 1980000, 1670000]
length_list = len(population_data)
print(length_list)
This will output the length of the list population_data, which is 5.
Here's another example with a list containing various data types:
list_of_things = ["apple", 7, False, 3.14]
length_list = len(list_of_things)
print(length_list)
Це виведе довжину списку list_of_things, яка дорівнює 4.
МЕТОД 2: ОТРИМАННЯ РОЗМІРУ СПИСКУ В PYTHON ЗА ДОПОМОГОЮ БІБЛІОТЕКИ NUMPY (PYTHON GET SIZE OF LIST )
Об'єкт масиву NumPy ndarray включає кілька корисних методів, які спрощують його використання. Ndarray широко використовується в аналізі даних, де важливі продуктивність і ефективність. NumPy пропонує функцію size(), яку можна використовувати для визначення довжини масиву або списку. Щоб використовувати NumPy, потрібно встановити пакет NumPy за допомогою pip, виконавши наступну команду:
> pip install numpy
Now, find the list size Python using numpy:
import numpy as np
monthly_expenses = [2200, 1500, 1800, 2000, 2300, 2100, 1900]
length_list = np.size(monthly_expenses)
print(length_list)
This will output the length of the list monthly_expenses, which is 7.
МЕТОД 3: ЯК ОТРИМАТИ ДОВЖИНУ СПИСКУ В PYTHON ЗА ДОПОМОГОЮ LENGTH_HINT() FUNCTION (LIST SIZE PYTHON)
Також можна використовувати функцію length_hint() з модуля operator, хоча вона використовується рідше, ніж len().
з оператора імпортувати length_hint
monthly_expenses = [2200, 1500, 1800, 2000, 2300, 2100, 1900]
length_list = length_hint(monthly_expenses)
print(length_list)
Це виведе довжину списку monthly_expenses, яка дорівнює 7.
МЕТОД 4: ЯК ОТРИМАТИ ДОВЖИНУ СПИСКУ В PYTHON ЗА ДОПОМОГОЮ ЦИКЛУ FOR
Інший метод визначення довжини списку в Python — це використання циклу for для перебору кожного елемента та їх підрахунку. Цей підхід часто називають наївним методом.
Хоча використання циклу for для підрахунку елементів є менш простим і менш поширеним, ніж функція len(), воно все одно може бути ефективним. Ось приклад, що ілюструє цей метод:
monthly_sales = [3200, 4200, 5500, 3800, 2900]
count = 0
for number in monthly_sales:
count += 1
print(count)
This will output the count of elements in the list monthly_sales, which is 5.
МЕТОД 5: ЯК ОТРИМАТИ ДОВЖИНУ СПИСКУ В PYTHON ЗА ДОПОМОГОЮ СПЕЦІАЛЬНОЇ ФУНКЦІЇ __LEN__()
Функція __len__ — це спеціальний метод в Python, який дозволяє об'єктам визначати власне поведінку для вбудованої функції len(). Коли ви викликаєте len() для об'єкта, для якого визначено метод __len__, Python викличе цей метод, щоб визначити довжину об'єкта.
daily_temperatures = [72, 68, 75, 70, 69, 71, 73]
list_length = daily_temperatures.__len__()
print(list_length)
Це виведе довжину списку daily_temperatures, яка дорівнює 7.
ЯК ОТРИМАТИ ДОВЖИНУ СПИСКУ В PYTHON?
У цьому розділі розглядається ефективність різних методів визначення довжини списку. Ефективність є вирішальним фактором при виборі найбільш підходящого методу для конкретного завдання. Вимірявши час виконання кожного методу, ви можете прийняти обгрунтоване рішення про те, який з них використовувати.
Наведений код аналізує час, необхідний для визначення довжини списку за допомогою різних методів. Він використовує бібліотеку time для запису часу початку та закінчення до і після виконання кожного методу. Список даних daily_sales передається в кожен метод, і час, що минув, вимірюється для кожного методу окремо. Цей аналіз дозволяє порівняти ефективність різних методів визначення довжини.
# Import time, length_hint and numpy modules
import time
from operator import length_hint
import numpy as np
daily_sales = [230, 540, 320, 410, 690, 840, 910, 320, 430, 570]
print('The items in the list are: ' + str(daily_sales))
# 1. built-in len() function
# Take note of the start time
begin_time_len = time.perf_counter()
length_of_list = len(daily_sales)
# Take note of the end time to determine execution time
end_time_len = str(time.perf_counter() - begin_time_len)
# 2. for loop
# Take note of the start time
begin_time_constraint = time.perf_counter()
# Initialize length as 0 and use the for loop
length = 0
for _ in daily_sales:
length += 1
# Take note of the end time to determine the execution time
end_time_constraint = str(time.perf_counter() - begin_time_constraint)
# 3. length_hint()
# Take note of the start time
begin_time_hint = time.perf_counter()
# length_hint()
length_hint_list = length_hint(daily_sales)
# Take note of the end time to determine execution time
end_time_hint = str(time.perf_counter() - begin_time_hint)
# Take note of the start time
begin_time_numpy = time.perf_counter()
# Use the NumPy module's size() method
length_numpy_list = np.size(daily_sales)
# Take note of the end time to determine execution time
end_time_numpy = str(time.perf_counter() - begin_time_numpy)
# Print out all the results
print('len() method execution time: ' + end_time_len)
print('for loop execution time: ' + end_time_constraint)
print('length_hint() method execution time: ' + end_time_hint)
print('NumPy module execution time: ' + end_time_numpy)
Поділіться своїми думками та допоможіть нам покращитися! Ваш відгук важливий для нас.
