TypeError: 'int' object is not subscriptable

一时失言乱红尘 2023-06-09 13:28 111阅读 0赞

1、错误描述

  1. E:\PycharmProjects\cmn\venv\Scripts\python.exe E:/PycharmProjects/cmn/venv/com.you.cmn/E.py
  2. Traceback (most recent call last):
  3. File "E:/PycharmProjects/cmn/venv/com.you.cmn/E.py", line 8, in <module>
  4. if(nums[i] % 2 == 0):
  5. TypeError: 'int' object is not subscriptable
  6. Process finished with exit code 1

2、错误原因

  1. 列表中的索引不能被使用(订阅)
  2. nums = [12,34,45,64,77,89,90,21,34,54];
  3. even = [];
  4. odd = [];
  5. i = 0;
  6. while i < len(nums):
  7. nums = nums.pop();
  8. if(nums[i] % 2 == 0):
  9. even.append(nums[i]);
  10. else:
  11. odd.append(num[i]);

3、解决办法

  1. 借助一个中间变量num
  2. nums = [12,34,45,64,77,89,90,21,34,54];
  3. even = [];
  4. odd = [];
  5. i = 0;
  6. while i < len(nums):
  7. num = nums.pop();
  8. if(num % 2 == 0):
  9. even.append(num);
  10. else:
  11. odd.append(num);
  12. print(even);
  13. print(odd);
  14. 结果:
  15. [54, 34, 90, 64, 34, 12]
  16. [21, 89, 77, 45]

发表评论

表情:
评论列表 (有 0 条评论,111人围观)

还没有评论,来说两句吧...

相关阅读