[英]How do you write a while loop using count on Python?
If a list of numbers can be defined as follows:如果一个数字列表可以定义如下:
x=[22,25,45,32,21]
Then, using the while loop count the number of items in the list.然后,使用 while 循环计算列表中的项目数。 Print the final count.打印最终计数。
I am having trouble.我遇到了麻烦。 I'm trying to write it using count and len() function.我正在尝试使用 count 和 len() function 来编写它。 Is there another way besides len() function.除了 len() function 还有其他方法吗? Thanks.谢谢。
If you can't use len
, consider that:如果您不能使用len
,请考虑:
You can use things like x.pop()
or del x[0]
to remove an item from the list.您可以使用x.pop()
或del x[0]
之类的东西从列表中删除项目。
tuple(x) == tuple()
(or equivalently, tuple(x) == tuple([])
) is True
for a list x
when and only when x
is empty. tuple(x) == tuple()
(或等价的tuple(x) == tuple([])
)对于列表x
当且仅当x
为空时为True
。
And, if you need to keep the original list intact, you can use xcopy = x[:]
to make a shallow copy of x
and use the above method on xcopy
.而且,如果您需要保持原始列表完整,可以使用xcopy = x[:]
制作x
的浅拷贝,并在xcopy
上使用上述方法。
This is homework but here is a solution:这是作业,但这是一个解决方案:
x=[22,25,45,32,21]
counter = 0
while counter < len(x):
counter += 1
print(counter)
#5
Without while:无时:
counter = 0
for i in x:
counter +=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.