python - 列表功能困难
问题描述
编写一个名为“counting”的函数,该函数将数字列表作为参数,并返回输入中 29.88 到 48.05 之间不包括这些端点的值的数量。(下面是我的代码)
def counting(number):
sum = 0
for x in number:
if (29.88 < x < 48.05):
sum = sum + x
return sum
如何返回输入中的值的数量而不是输入的第一个数字?
解决方案
your return statement is indented too deep; you should return it after the for loop. also sum
is not a good name as it is a built-in function that you overwrite.
and you should add 1
to the sum (you are counting) and not x
itself.
you could also try this using the built-in function sum
:
def counting(number):
return sum(29.88 < x < 48.05 for x in number)
(this is actually short for sum(1 for x in number if 29.88 < x < 48.05)
and works because True
is basically 1
and False
is basically 0
).
推荐阅读
- mysql - #1064 - 您的 SQL 语法有错误 - 不存在 - xampp
- java - Java 信任库即时更新。这种行为可能吗?
- python - 无法获取 Django HttpResponse
- html - 如何使用 vba 更改 html 类名?
- angular - 如何使用switchMap取消http请求?
- tsql - 如何在 SQL 的 DATEFROMPARTS 中使用计算值
- java - Java / LibGDX 在全屏窗口前显示 JOptionPane
- azure-devops - 有没有办法在容量跟踪器中使用继承的 Activity 类型
- adobe-indesign - 在 InDesign 中,如何以编程方式将活动文档中的特定单词显示在视图中?
- python - 如何在 slite3 表头中添加过滤器下拉菜单