How to get list index and element simultaneously in Python?
24896 просмотра
2 ответа
I find myself frequently writing code like this:
k = 0
for i in mylist:
# y[k] = some function of i
k += 1
Instead, I could do
for k in range(K):
# y[k] = some function of mylist[k]
but that doesn't seem "pythonic". (You know... indexing. Ick!) Is there some syntax that allows me to extract both the index (k) and the element (i) simultaneously using either a loop, list comprehension, or generator? The task is in scientific computing, so there is a lot of stuff in the loop body, making a list comprehension probably not powerful enough on its own, I think.
I welcome tips on related concepts, too, that I might not have even though of. Thank you.
Автор: Steve Tjoa Источник Размещён: 12.11.2019 09:58Ответы (2)
51 плюса
You can use enumerate
:
for k,i in enumerate(mylist):
#do something with index k
#do something with element i
More information about looping techniques.
Edit:
As pointed out in the comments, using other variable names like
for i, item in enumerate(mylist):
makes it easier to read and understand your code in the long run. Normally you should use i
, j
, k
for numbers and meaningful variable names to describe elements of a list.
I.e. if you have e.g. a list of books and iterate over it, then you should name the variable book
.
17 плюса
enumerate
is the answer:
for index, element in enumerate(iterable):
#work with index and element
Автор: SilentGhost
Размещён: 15.01.2010 02:58
Вопросы из категории :
- python Обработка XML в Python
- python Как я могу использовать Python itertools.groupby ()?
- python Python: На какой ОС я работаю?
- python Как я могу создать непосредственно исполняемое кроссплатформенное приложение с графическим интерфейсом на Python?
- python Вызов функции модуля с использованием его имени (строки)
- python Звук Питона («Колокол»)
- python Regex и unicode
- python Создать зашифрованный ZIP-файл в Python
- python Создайте базовый итератор Python
- python Функция транспонирования / распаковки (обратная сторона zip)?
- python Каков наилучший способ разбора аргументов командной строки?
- python Формат чисел в строки в Python
- python Как загрузить файл через HTTP с помощью Python?
- python Is there any difference between "foo is None" and "foo == None"?
- python Как запустить сценарий Python как службу в Windows?
- python Нахождение каких методов у объекта Python
- python Как отсортировать список строк?
- python Что ** (двойная звезда / звездочка) и * (звездочка / звездочка) делают для параметров?
- python What is the purpose of class methods?
- python Какой лучший способ вернуть несколько значений из функции в Python?