python-3.x - 索引错误:列表索引超出范围(Python 初学者,while 循环)
问题描述
我正在尝试制作一个将列表作为输入参数的函数。我将使用 while 循环遍历列表并跟踪列表中包含的整数和字符串的数量。这是我到目前为止所拥有的:
def usingwhileloop(mylist):
count = 0
int_total = 0
str_total = 0
while count <= len(mylist):
if isinstance(mylist[count], int) == True:
int_total = int_total + 1
elif isinstance((mylist[count]), str) == True:
str_total = str_total + 1
count = count + 1
newlist = [int_total, str_total]
return newlist
当我运行像 [1, 2, 3, “a”, “b”, 4] 这样的列表时,它应该返回 [4, 2] 但我得到以下错误:“第 51 行,在 usingwhileloop if isinstance(what [count], int) == True: IndexError: list index out of range "
我究竟做错了什么?我在while循环中挣扎......
解决方案
如果您确实需要 while 循环,请通过josephting查看答案。
对于您展示的示例,您不需要while
循环,例如
"""
Some simple functions
"""
def count_types_ex1(items):
"""Count types from a list"""
counters = [0, 0]
for item in items:
if isinstance(item, int):
counters[0] += 1
elif isinstance(item, str):
counters[1] += 1
return counters
print(count_types_ex1([1, 2, 3, 'a', 'b', 4]))
def count_types_ex2(items):
"""Count types from a list"""
check_type = lambda x: [int(isinstance(x, int)), int(isinstance(x, str))]
counters = [check_type(x) for x in items]
return sum(x[0] for x in counters), sum(x[1] for x in counters)
print(count_types_ex2([1, 2, 3, 'a', 'b', 4]))
输出:
[4, 2]
(4, 2)
推荐阅读
- jupyter-notebook - notebook/static/components/的源代码在哪里?
- javascript - 使用双查询字符串在地址栏中发送邮件
- html - 是否可以在常规 web 上触发内置的 SVG 表示属性功能?
- python - 使用 Web2py/Pydal 将字段定义为无符号整数
- regex - 使用 sed 修复有问题的文本文件的行
- mysql - 谷歌云代理 r2dbc mysql 驱动程序在谷歌上连接 mysql 一段时间后遇到关闭的连接与错误的证书
- angular - 角度不能在函数内调用函数/变量
- c++ - 如何优化用于对 Burrows Wheeler 变换的 Class 对象进行排序的堆排序?
- excel - 寻找更好的方法来编写这个可以提高速度的复制循环
- c# - Angular-总是收到 400 Bad Request 响应