Перебрать список в Python
Список эквивалентен массивам на других языках с дополнительным преимуществом в виде динамического размера. В Python список - это тип контейнера в структурах данных, который используется для одновременного хранения нескольких данных. В отличие от наборов, списки в Python упорядочены и имеют определенное количество.
Существует несколько способов перебора списка в Python. Давайте посмотрим все различные способы перебора списка в Python и сравнение их производительности.
Method #1: Using For loop
Python3
# Python3 code to iterate over a listlist = [1, 3, 5, 7, 9] # Using for loopfor i in list: print(i) |
Выход:
1 3 5 7 9
Method #2: For loop and range()
In case we want to use the traditional for loop which iterates from number x to number y.
Python3
# Python3 code to iterate over a listlist = [1, 3, 5, 7, 9] # getting length of listlength = len(list) # Iterating the index# same as "for i in range(len(list))"for i in range(length): print(list[i]) |
Выход:
1 3 5 7 9
Iterating using the index is not recommended if we can iterate over the elements (as done in Method #1).
Method #3: Using while loop
Python3
# Python3 code to iterate over a listlist = [1, 3, 5, 7, 9] # Getting length of listlength = len(list)i = 0 # Iterating using while loopwhile i < length: print(list[i]) i += 1 |
Выход:
1 3 5 7 9
Method #4: Using list comprehension (Possibly the most concrete way).
Python3
# Python3 code to iterate over a listlist = [1, 3, 5, 7, 9] # Using list comprehension[print(i) for i in list] |
Выход:
1 3 5 7 9
Method #5: Using enumerate()
If we want to convert the list into an iterable list of tuples (or get the index based on a condition check, for example in linear search you might need to save the index of minimum element), you can use the enumerate() function.
Python3
# Python3 code to iterate over a listlist = [1, 3, 5, 7, 9] # Using enumerate()for i, val in enumerate(list): print (i, ",",val) |
Выход:
0, 1 1, 3 2, 5 3, 7 4, 9
Note: Even method #2 can be used to find the index, but method #1 can’t (Unless an extra variable is incremented every iteration) and method #5 gives a concise representation of this indexing.
Method #6: Using Numpy
For very large n-dimensional lists (for example an image array), it is sometimes better to use an external library such as numpy.
Python3
# Python program for# iterating over arrayimport numpy as geek # creating an array using # arrange methoda = geek.arange(9) # shape array with 3 rows # and 4 columnsa = a.reshape(3, 3) # iterating an arrayfor x in geek.nditer(a): print(x) |
Выход:
0 1 2 3 4 5 6 7 8
Мы можем использовать np.ndenumerate (), чтобы имитировать поведение enumerate. Дополнительная мощность numpy проистекает из того факта, что мы даже можем контролировать способ посещения элементов (порядок Fortran, а не порядок C, скажем :)), но одно предостережение заключается в том, что np.nditer обрабатывает массив как доступный только для чтения. по умолчанию, поэтому необходимо передать дополнительные флаги, такие как op_flags = ['readwrite'], чтобы иметь возможность изменять элементы.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.