Перебор по списку. Добавьте элемент к имени списка, если индекс элемента можно разделить на два без остатка. Если при делении индекса на два есть остаток, добавьте элемент к возрасту списка. Индексы списка начинаются с 0. enumerate делает индекс элемента доступным при итерации списка. Проверка остатка от деления выполняется с помощью оператора по модулю.
lst = ['John', 21, 'Smith', 30, 'James', 25]
#Create list name to store the names
name = []
#Create list age to store the age
age = []
# use for loop to access every element of lst
# using enumerate(lst) let's us access the index of every element in the variable index see reference [0]
# The indexes of the list elements are as following:
# John: 0, 21: 1, Smith: 2, 30: 3, James: 4, 25: 5
for index,element in enumerate(lst):
#Check if the index of an element can be divided by 2 without a remainder
#This is true for the elements John, Smith and James:
#0 / 2 = 0 remainder 0
#2 / 2 = 1 remainder 0
#4 / 2 = 2 remainder 0
if index % 2 == 0:
name.append(element)
# If the division of the index of an element yields remainder, add the element to the list age
# This is true for the elements 21, 30 and 25:
# 1 / 2 = 0 remainder 1
# 3 / 2 = 1 remainder 1
# 5 / 2 = 2 remainder 1
else:
age.append(element)
print(name)
print(age)
Ссылки:
[0] https://docs.python.org/3/library/functions.html#enumerate
[1] https://docs.python.org/3.3/reference/expressions.html#binary -arithmeti c -операций .