【发布时间】:2021-07-17 02:50:02
【问题描述】:
所以目标是接受整数输入,使用第一个数字来说明列表中实际有多少整数,最后一个数字是范围(所以在这种情况下它是 100,所以所有大于或等于 100列表中的内容应在打印中删除)
在最后的语句中,第一个和最后一个数字都应该被删除
这是我能想到的,但我遇到了两个问题:在上半场,它删除了除“3000”之外的所有内容,它似乎只是列表中没有被删除的元素,因为, '140' 和 '100' 都被删除了。
第二个问题在底部的打印语句中,我不完全确定为什么,但是它给出“IndexError: list index out of range”
用户输入示例:5 50 60 140 3000 75 100
numbers = []
integers = int(input())
while True:
integers = int(input())
numbers.append(integers)
firsti = numbers[0]
if len(numbers) > firsti + 1: #if the number of items in list (numbers) > the first list item PLUS ONE
numbers.remove(numbers[0]) #remove the first item
lastdigi = numbers[-1]
for number in numbers:
if number >= lastdigi: #removes all numbers >= last digi
numbers.remove(number)
break #and prints the rest
listnum = len(numbers) #this whole section is to try and print the numbers from the list
while listnum >= 0: #and match the example output
print (numbers[0], end=',')
numbers.remove(numbers[0])
print(numbers)
#example output: '50,60,75,'
#my output: '50,60,3000,75,'
【问题讨论】:
-
您写道,last 数字是范围。但是您使用第二个数字作为范围。
-
你不能使用推导来消除超过某个数字的值吗?即
numbers = [x for x in numbers if x < value]?
标签: python error-handling index-error