在删除列表中的前三位数字后的第二次尝试中,“ for循环”似乎不接受删除的数字,而是以某种我不理解的方式对其进行了格式化。为什么要这样做,我该如何解决?
nums = [3,3,1,3,2,5,6,3]
#iterating through list
total = 0
for number in nums:
total+=number
print ("sum of all values in list: ",total)
print("sum of all values in list: ", sum(nums))
print (len(nums))
del nums[0:3] #deletes [3,3,1]
for number in nums:
total+=number
print ("sum of all values in list: ",total)
print("sum of all values in list: ", sum(nums))
print (len(nums))
结果:
sum of all values in list: 26
sum of all values in list: 26
8
sum of all values in list: 45
sum of all values in list: 19
5
Process finished with exit code 0
答案 0 :(得分:1)
nums = [3,3,1,3,2,5,6,3]
total = 0
for number in nums:
total+=number
print ("sum of all values in list: ",total)
总计值为26
del nums[0:3]
您已从nums中删除了[3,3,1],现在该列表已变为[3、2、5、6、3]
for number in nums:
total+=number
print ("sum of all values in list: ",total)
总计未重置为0,因此总计为26 + 3 + 2 + 5 + 6 + 3 = 45
print("sum of all values in list: ", sum(nums))
由于删除前3个条目后列表现在为[3、2、5、6、3],所以sum(nums)给出3 + 2 + 5 + 6 + 3 = 19
希望有帮助:)