I would like to loop through a list in python and usually I do in this way:
let's imagine a list into a variable called 'movie' where I want to print the even into a variable 'authors' and the odd into 'stars'. I would do like this:
stars = movies[0] #print the first
authors = movies[1] #print the second
for i in range(0, len(movies), 2):
stars = movies[0+i]
authors = movies[1+i]
But how can i do in this other way?
stars, authors = movies[0:2]
for i in range(0, len(movies), 2):
stars #how can i insert "i"?
You can use slicing:
stars=movies[::2]
authors=movies[1::2]
stars
consists of every other sample in the movies
array, hence the step of 2. It starts with the 0th index, which was omitted above. You could also write stars=movies[0::2]
.
authors
also uses a step of 2, but starts with the first index in movies
.
You can check out the basics of indexing and slicing here .
Assuming you don't need the value of movies afterwards you can use extended iterable unpacking
while movies:
stars, authors, *movies = movies
只需使用三层切片(开始:结束:步骤):
stars, authors = movies[::2], movies[1::2]
for i in range(0, len(movies), 2):
stars, authors = movies[i:i+2]
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.