包阅导读总结
1. 关键词:Python、sum() 函数、累加、可迭代对象、起始值
2. 总结:
本文介绍了 Python 中的 sum() 函数,包括其使用方法、适用的数据类型、起始值的设置、在计算中的应用如求和、求平均值等,强调了其便利性和可读性。
3. 主要内容:
– Python 中求和的常规方法
– 通过简单的加法运算
– 使用 for 循环累加
– 自定义函数求和
– sum() 函数
– 引入版本:Python 2.3
– 优势:可读性强,简化求和操作
– 可用于列表、元组、集合、范围和字典
– 两个参数:必选的可迭代对象和可选的起始值
– sum() 函数的应用
– 计算范围值的平方和
– 结合输入计算总和
– 计算数字的平均值
思维导图:
文章地址:https://thenewstack.io/what-is-pythons-sum-function-and-how-do-you-use-it/
文章来源:thenewstack.io
作者:Jack Wallen
发布时间:2024/8/9 15:27
语言:英文
总字数:1184字
预计阅读时间:5分钟
评分:87分
标签:Python,sum() 函数,数据结构,代码效率,可读性
以下为原文内容
本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com
In Python, you could always do something like this:
The above code is simple: It adds 3 to 5 and prints the total. You could even do something like this:
Once again, Python will total and print the value. And given that adding several numbers together is a widely used step in computations, it’s pretty handy that Python can do this.
You could even use a for loop to sum a string of numbers together like this:
a = [3, 5, 7, 10] total = 0
for number in a: total += number
print(total) |
The above would output the same value as the two-line code above it. In the above code, total
is initialized to 0, and then the variable acts as an accumulator as it iterates through the loop. We could also create a function that will do the same and can be reused throughout the application. Such a function might look like this:
def total_numbers(a): total = 0 for number in a: total += number return total
print(total_numbers([3, 5, 7, 10])) |
However, there’s a built-in function that’s much better to use. The function in question is sum()
. One of the primary reasons for using this function is readability. Instead of having to write for
loops or recursions, sum()
takes care of all that for you.
The sum()
function wasn’t introduced until Python 2.3 and serves as a Pythonic solution to summing numbers.
Using sum()
is very easy. For instance:
a = sum([3, 5, 7, 10]) print(a) |
Pretty simple.
You could also use sum()
like this:
a = [3, 5, 7, 10] result = sum(a) print(“The sum of the numbers = “, result) |
The sum()
function can be used with lists, tuples, sets, ranges and dictionaries.
Let me show you how each might look:
- List: sum([3, 5, 7, 10])
- Tuple: sum((3, 5, 7, 10))
- Set: sum({3, 5, 7, 10})
- Range: sum(range(3, 10))
- Dictionary: sum({3: “three”, 5: “five”, 7: “seven”, 10: “ten”})
With the exception of the range, all of the above will total 25. The range, on the other hand, will total 42.
You could also get a bit more fancy with your math. For example, let’s say you want to compute the sum of the squares from a range of values. That might look something like this:
sum([x ** 2 for x in range(1, 10)]) |
The total from the above would be 285.
The sum()
function has two arguments: the required iterable (the numbers to be iterated through) and the optional start
. The start
argument comes in very handy. Let’s say you want to add a list of iterables together but you want to start out with a predefined starting value. Without the start
argument, the starting value is always assumed to be 0. Take a look at the following line:
The total is 25 because our starting value is the default, 0. But what if we want our starting value to be, say, 100. For that, you could use the start
argument like this:
sum([3, 5, 7, 10], start=100) |
Our total is now 125.
But why not just add the 100 to the list, like so:
You could do that and it would work just fine. But let me give you an example where using the start
argument illustrates why it can be necessary.
Let’s say you want to add the total amount of a sale but you want to start off by giving a discount. For example, the discount might be $200.00 off. How would you do that? With the start
argument.
Let’s say you have a list of dollar amounts that looks like this:
sales = [3000, 5000, 7000, 10000] |
You could set an initial value like this:
Finish up the code like so:
sales = [3000, 5000, 7000, 10000] initial_value = –200 total_sales = sum(sales, initial_value) print(“Total sales amount:”, total_sales) |
The output of the above would be:
Total sales amount: 24800.
What we did above was define a variable to use for the starting value and then plug it in for the total_sales
summation. We could always skip the initial_value
variable and hard code the start value like this:
total_sales = sum(sales, start=-200) |
It’s also possible to use sum()
while using input
, but it’s a bit trickier.
What we have to do is first accept input for our variables with the following:
a = int(input(“Type a number: “)) b = int(input(“Type a number: “)) c = int(input(“Type a number: “)) |
Next, we define a new variable from the user input like so:
We can then total the inputted numbers with the sum()
function:
Finally, we print it out:
The entire code looks like this:
a = int(input(“Type a number: “)) b = int(input(“Type a number: “)) c = int(input(“Type a number: “)) my_list = [a, b, c] total = sum(my_list) print(total) |
We could also use sum()
to calculate the average of numbers. This also requires the len()
function, which takes an object as an argument and returns the length of that object. This code looks like this:
numbers = [3, 5, 7, 10] num = sum(numbers) average= num/len(numbers) print (average) |
What the above does is devise the sum of the numbers from num = sum(numbers)
by the length of the list (which is 4). So 25 divided by 4 equals 6.25.
The Python sum()
function will come in very handy as you continue your journey with this widely used language.
YOUTUBE.COM/THENEWSTACK
Tech moves fast, don’t miss an episode. Subscribe to our YouTubechannel to stream all our podcasts, interviews, demos, and more.