Python 如何得到这里所有元素的和?
这里的错误是,给出的元素是4,5,6,但只有最后一个元素“6”用于求三次和 我希望我回答了评论中提出的所有问题 任何稍加解释的想法都会受到高度赞赏。…Python之禅:简单比复杂好 无论您构建什么自定义函数,它都不会比内置函数快。Python 如何得到这里所有元素的和?,python,list,queue,Python,List,Queue,这里的错误是,给出的元素是4,5,6,但只有最后一个元素“6”用于求三次和 我希望我回答了评论中提出的所有问题 任何稍加解释的想法都会受到高度赞赏。…Python之禅:简单比复杂好 无论您构建什么自定义函数,它都不会比内置函数快。 Enter element=4 Enter element=5 Enter element=6 Enter the number of elements in the queue for addition=3 The list is: [6, 6, 6] the su
Enter element=4
Enter element=5
Enter element=6
Enter the number of elements in the queue for addition=3
The list is:
[6, 6, 6]
the sum of items :
18
如果您仍然需要自定义函数
python有
sum
?是的,我们试过了,但它在队列中仍然不起作用……它给出了相同的错误@mzy您的队列只是一个列表,所以我不知道这是怎么起作用的,但是,还有什么错误?queue.append(item)
在循环中每次都会添加相同的变量item
。是的,根据实际发布的代码,甚至不清楚item
从何而来。我知道内置更好…但我应该在这里使用队列…所以任何与代码求和都很有用…我在回答中添加了自定义函数是的,我正在实现它们……非常感谢您将这两个部分(简单部分和自定义部分)结合在一起。它工作得非常好。非常感谢您……@stackz
Enter element=4
Enter element=5
Enter element=6
Enter the number of elements in the queue for addition=3
The list is:
[6, 6, 6]
the sum of items :
18
l = [6,6,6]
total = sum(l)
print('The list is: {}'.format(l)
print('the sum of items : {}'.format(total))
def arr_sum(arr):
holder = 0
if len(arr) == 0:
return 0
else:
holder = [holder + i for i in arr if type(i) == int]
return holder