1、错误描述
E:PycharmProjectscmnvenvScriptspython.exe E:/PycharmProjects/cmn/venv/com.you.cmn/E.py
Traceback (most recent call last):
File "E:/PycharmProjects/cmn/venv/com.you.cmn/E.py", line 8, in <module>
if(nums[i] % 2 == 0):
TypeError: 'int' object is not subscriptable
Process finished with exit code 1
2、错误原因
列表中的索引不能被使用(订阅)
nums = [12,34,45,64,77,89,90,21,34,54];
even = [];
odd = [];
i = 0;
while i < len(nums):
nums = nums.pop();
if(nums[i] % 2 == 0):
even.append(nums[i]);
else:
odd.append(num[i]);
3、解决办法
借助一个中间变量num
nums = [12,34,45,64,77,89,90,21,34,54];
even = [];
odd = [];
i = 0;
while i < len(nums):
num = nums.pop();
if(num % 2 == 0):
even.append(num);
else:
odd.append(num);
print(even);
print(odd);
结果:
[54, 34, 90, 64, 34, 12]
[21, 89, 77, 45]