Write a function named sum_elements to compute the sum of all the elements of each tuple stored inside a list of tuples and return a list of these sums. The number of elements in the tuples might vary. For example, if lst_tpl = [(1,2,3),(5,6),(7,)], sum_elements(lst_tpl) should return [6, 11, 7]
时间: 2023-12-04 16:02:49 浏览: 104
Sure, I can help you with that! Here's the implementation of the function sum_elements:
```
def sum_elements(lst_tpl):
sum_list = []
for tpl in lst_tpl:
tpl_sum = sum(tpl)
sum_list.append(tpl_sum)
return sum_list
```
In this function, we first create an empty list called `sum_list` which will store the sum of each tuple. Then, we iterate through each tuple in the given list of tuples `lst_tpl`. For each tuple, we use the built-in `sum` function to calculate its sum and store it in a variable called `tpl_sum`. Finally, we append this `tpl_sum` to the `sum_list`. After we have looped through all the tuples, we return this `sum_list`.
You can test this function by calling it with a list of tuples, like this:
```
lst_tpl = [(1,2,3),(5,6),(7,)]
print(sum_elements(lst_tpl))
```
This will output `[6, 11, 7]`, which is the expected result.
阅读全文