简体   繁体   English

将字符串追加到列表中

[英]Append string into a list

I would like to loop through a list in python and usually I do in this way: 我想在python中遍历一个列表,通常我是这样做的:

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. starsmovies数组中的所有其他样本组成,因此为2。它从第0个索引开始,在上面已省略。 You could also write stars=movies[0::2] . 您还可以编写stars=movies[0::2]

authors also uses a step of 2, but starts with the first index in movies . authors也使用2的步长,但从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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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