简体   繁体   中英

Splitting integers and strings into other lists

I have this

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

and I want to split them into the following

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

You can do this. Don't use keywords and built-in names as variable names.

Using Slicing

Understanding Slicing Notation

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

Or you can use List Comprehension

List Comprehension Reference

name=[val for idx,val in enumerate(lst) if idx%2==0]
age=[val for idx,val in enumerate(lst) if idx%2==1]

Iterate over the list. Append an element to the list name if the index of the element can be divided by two without remainder. If there is a remainder when dividing the index by two append the element to the list age. List indexes start at 0. enumerate makes the index of an element available while iterating a list. Checking remainder of division is done with the modulo operator.

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)

References:

[0] https://docs.python.org/3/library/functions.html#enumerate
[1] https://docs.python.org/3.3/reference/expressions.html#binary-arithmetic-operations .

A less convenient way is to use list indexing:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM