在附加列表(用户输入)(Python)中计数和分离年龄
我自己试图自己弄清楚这一点,但我无法获得想要的结果,而且我无法通过互联网找到正确的答案。我有一块代码,要求用户10年龄并将其存储在附录列表中,问题是我可以按年龄分开它们,但我不知道如何按年龄组来计数数量。我尝试寻找文档,但其中大多数是带有已知值列表的示例。谁能给我一些建议? 到目前为止,这是我的代码:
age = []
for i in range (10):
ag = int (input("Write your age"))
age.append(ag)
print ("The number of kids are: ")
for i in range (10):
if age [i] < 12:
print (age [i])
print ("The number of teenagers are: ")
for i in range (10):
if age [i] >=12 and age [i] < 17:
print (age [i])
print ("The number of adults are: ")
for i in range (10):
if age [i] >= 18:
print (age [i])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅使用一个循环,一个构建数据的循环,同时为每个类别增量计数器
Use only one loop, the one that builds the data, at the same time increment counter for each category
一旦收集了年龄,就可以将它们过滤为子列表,类似:
上面的示例是使用Python的功能,称为
您也可以明确地循环到项目上,并在需要时打印/填充值:
once you've collected your ages, you could filter them into sub-lists, something like:
The above example is using a feature of python called list comprehensions
[value for value in list (if condition)]
You could also loop over the items explicitly and print/populate values if you wanted: