Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - 在Python中汇总一个数字列表(Sum a list of numbers in Python)

I have a list of numbers such as [1,2,3,4,5...] , and I want to calculate (1+2)/2 and for the second, (2+3)/2 and the third, (3+4)/2 , and so on.

(我有一个数字列表,如[1,2,3,4,5...] ,我想计算(1+2)/2和第二, (2+3)/2和第三, (3+4)/2 ,依此类推。)

How can I do that?

(我怎样才能做到这一点?)

I would like to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on.

(我想将第一个数字与第二个数字相加并除以2,然后将第二个数字与第三个相加并除以2,依此类推。)

Also, how can I sum a list of numbers?

(另外,我如何总结一个数字列表?)

a = [1, 2, 3, 4, 5, ...]

Is it:

(是吗:)

b = sum(a)
print b

to get one number?

(得到一个号码?)

This doesn't work for me.

(这对我不起作用。)

  ask by layo translate from so

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

1 Answer

0 votes
by (71.8m points)

Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc.

(问题1:你想要(元素0 +元素1)/ 2,(元素1 +元素2)/ 2,......等)

We make two lists: one of every element except the first, and one of every element except the last.

(我们制作两个列表:除了第一个之外的每个元素之一,以及除了最后一个之外的每个元素之一。)

Then the averages we want are the averages of each pair taken from the two lists.

(然后我们想要的平均值是从两个列表中取得的每对的平均值。)

We use zip to take pairs from two lists.

(我们使用zip来从两个列表中获取对。)

I assume you want to see decimals in the result, even though your input values are integers.

(我假设您希望在结果中看到小数,即使您的输入值是整数。)

By default, Python does integer division: it discards the remainder.

(默认情况下,Python执行整数除法:它会丢弃余数。)

To divide things through all the way, we need to use floating-point numbers.

(为了将事情分开,我们需要使用浮点数。)

Fortunately, dividing an int by a float will produce a float, so we just use 2.0 for our divisor instead of 2 .

(幸运的是,将一个int除以float会产生一个浮点数,所以我们只使用2.0作为除数而不是2 。)

Thus:

(从而:)

averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]

Question 2:

(问题2:)

That use of sum should work fine.

(使用sum应该可以正常工作。)

The following works:

(以下作品:)

a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45

Also, you don't need to assign everything to a variable at every step along the way.

(此外,您不需要在整个过程中的每一步都将所有内容分配给变量。)

print sum(a) works just fine.

(print sum(a)工作正常。)

You will have to be more specific about exactly what you wrote and how it isn't working.

(您必须更准确地了解您所写的内容以及它的工作方式。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...