英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论