Разбиение целых чисел и строк в другие списки - PullRequest
0 голосов
/ 23 января 2020

У меня есть

list = ['John', 21, 'Smith', 30, 'James', 25]

, и я хочу разделить их на следующие

name = ['John', 'Smith', 'James']
age = [21, 30, 25]

Ответы [ 3 ]

3 голосов
/ 23 января 2020

Вы можете сделать это. Не используйте имена keywords и built-in в качестве имен переменных.

Использование нарезки

Понимание обозначения нарезки

lst=['John', 21, 'Smith', 30, 'James', 25]
name=lst[::2] 
age=lst[1::2]

Или вы можете использовать Понимание списка

Справочник по пониманию списка

name=[val for idx,val in enumerate(lst) if idx%2==0]
age=[val for idx,val in enumerate(lst) if idx%2==1]
1 голос
/ 23 января 2020

Перебор по списку. Добавьте элемент к имени списка, если индекс элемента можно разделить на два без остатка. Если при делении индекса на два есть остаток, добавьте элемент к возрасту списка. Индексы списка начинаются с 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 -операций .

0 голосов
/ 23 января 2020

Менее удобный способ - использовать индексацию списка:

list = ['John', 21, 'Smith', 30, 'James', 25]
name=[list[0],list[2],list[4]]
print(name)
age=[list[1],list[3],list[5]]
print(age)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...