Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

python - 用于列表的循环数学(For loop math with list)

Say I have a hypothetical list such as:

(假设我有一个假设的清单,例如:)

my_list=['0','2','3','5','1']

I want to make a new list by having each number in my list subtract each other in a sequence to look something like this (each number subtracts to the left):

(我想通过让列表中的每个数字依次相减来制作一个新列表,看起来像这样(每个数字都减去左侧):)

0-nothing=0
2-0=2
3-2=1
5-3=2
1-5=-4
new_list=['0','2','1','2','-4']

I feel like this could be solved in a for loop.

(我觉得这可以在for循环中解决。)

Here's my terrible for loop, and me also doing it manually:

(这是我糟糕的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)

Each thing I try is a disaster.

(我尝试的每一件事都是一场灾难。)

Am I going the wrong way with my substandard logic?

(我使用不合标准的逻辑会走错路吗?)

  ask by AJDouglas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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遍历索引,然后根据indexindex-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强制类型转换。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...