假设我有一个假设清单,例如:
my_list=['0','2','3','5','1']
我想通过让列表中的每个数字依次相减来制作一个新列表,看起来像这样(每个数字都减去左侧):
0-nothing=0
2-0=2
3-2=1
5-3=2
1-5=-4
new_list=['0','2','1','2','-4']
我觉得这可以在for循环中解决。这是我糟糕的for循环,我也手动进行:
new_list = []
for item in my_list:
new_list.append(float(item)) #Converting strings into floats
print(new_list)
#for number in my_list:
#print(list(str((number-[0:])))) #completely wrong
new_list[0]=new_list[0]
new_list[1]=new_list[1]-new_list[0]
new_list[2]=new_list[2]-new_list[1] #Won't work past this point as the numbers in the list are now new.
new_list[3]=new_list[3]-new_list[2]
new_list[4]=new_list[4]-new_list[3]
print(new_list)
我尝试的每一件事都是一场灾难。我的标准逻辑不正确吗?
要使用for循环执行此操作,可以使用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)
您还可以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)
注意:如果您的列表是int类型,则可以摆脱str
/int
强制转换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句