怎样用更简洁的代码从列表中同时为两个变量编写循环

huangapple go评论70阅读模式
英文:

How to write a loop for two variables at a time from a list in a more clean code

问题

以下是代码部分的翻译:

vals = [1, 3, 3, 6, 8, 12]

以下是您要执行的操作:

3-1,3-3,6-3,8-6,12-8

以下是您编写的代码:

for i in range(len(vals) - 1):
  j = i + 1
  val1, val2 = vals[i], vals[j]
  r = val2 - val1
  print(r)

它返回的结果是2, 0, 3, 2, 4。

是否有更简洁的代码来执行这个操作?

英文:

I have a list of values and I want to get them by pairs and perform an operation with this pair... Any operation. Can be subtraction, since I am more interested in knowing the best way to get the variables by pairs for this loop.

vals = [1, 3, 3, 6, 8, 12]

And I want to perform operations in pairs:
3-1 , 3-3, 6-3, 8-6, 12-8

And I wrote this code:

for i in range( len(vals)-1 ):
  j = i+1
  val1, val2 = vals[i], vals[j]
  r = val2 - val1
  print(r)

It returns 2, 0, 3, 2, 4.

Is there a way to write this operation with a cleaner code?

答案1

得分: 1

一种选择是使用 zip 将每个项目与后面的项目组合成一个可迭代对象,这样你就可以像这样做:

>>> vals = [1, 3, 3, 6, 8, 12]
>>> print(*(j - i for i, j in zip(vals, vals[1:])))
2 0 3 2 4
英文:

One option is to use zip to combine each item with the following one in a single iterable, which lets you do something like:

>>> vals = [1, 3, 3, 6, 8, 12]
>>> print(*(j - i for i, j in zip(vals, vals[1:])))
2 0 3 2 4

huangapple
  • 本文由 发表于 2023年3月7日 11:23:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定