to do this with a for-loop, you can use range
to go over the indexes, then calculate the element based on index
and index-1
, like this:
(为此,可以使用range
遍历索引,然后根据index
和index-1
计算元素,如下所示:)
my_list=['0','2','3','5','1']
new_list = [my_list[0]]
for index in range(1, len(my_list)):
new_list.append(str(int(my_list[index]) - int(my_list[index-1])))
print(new_list)
you can also use zip
to go over the adjacent elements without dealing with indexes, like this:
(您还可以使用zip
来遍历相邻元素,而无需处理索引,如下所示:)
my_list=['0','2','3','5','1']
new_list = [my_list[0]]
for first,second in zip(my_list, my_list[1:]):
new_list.append(str(int(second) - int(first)))
print(new_list)
NOTE: you could get rid of the str
/ int
casts if your lists were of type int.
(注意:如果您的列表类型为int,则可以摆脱str
/ int
强制类型转换。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…