如何在Python中高效地对整数数组中的所有项进行加法或减法操作?

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

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).

huangapple
  • 本文由 发表于 2023年4月13日 21:20:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005944.html
匿名

发表评论

匿名网友

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

确定