英文:
How do I add or subtract all the items in an array of integers efficiently in python?
问题
以下是翻译好的代码部分:
这个问题与特定问题不太相关,而更多地与我在使用数组时持续遇到的问题有关。
假设我有这样一个数组:
x = [4,7,11]
如果我想把它们全部相加,我会这样做:
for i in range(len(x)-1):
x[i+1] = x[i]+x[i+1]
x[i] = 0
然后我会接着做:
for i in x:
if i == 0:
x.remove(i)
尽管这个方法可行,但非常慢,绝对不是最有效的方法,而且会占用额外的几行代码。
如果有人有更好的方法,请告诉我。每次这样做都会让我感到非常痛苦。
英文:
this question is less about a specific issue, and more about a problem that I continuously have while working with arrays.
Say I have an array like this:
x = [4,7,11]
If I wanted to add al of these together, what I would do is:
for i in range(len(x)-1):
x[i+1] = x[i]+x[i+1]
x[i] = 0
I would then follow this with:
for i in x:
if i == 0:
x.remove(i)
Although this works, It's incredibly slow and definitely not the most efficient way to do this, besides taking up several extra lines.
If anyone has a better way to do this, please tell me. This physically hurts me every time I do it.
答案1
得分: 1
As TYZ said, you can simply use sum(x)
for getting the sum of a numerical list.
For subtraction where you subtract later items from the first item, you can use x[0]-sum(x[1:])
.
英文:
As TYZ said, you can simply use sum(x)
for getting the sum of a numerical list.
For subtraction where you subtract later items from the first item, you can use x[0]-sum(x[1:])
.
答案2
得分: 0
你可以简单地使用 sum
函数:sum(x)
。
英文:
You can simply just use the sum
function: sum(x)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论