![](/img/trans.png)
[英]how to print 3 numbers greater than a specific number of a list in python?
[英]How do you remove numbers greater than or equal to a specified number within a list, in python
所以目標是采用 integer 輸入,使用第一個數字來表示列表中實際有多少個整數,最后一個數字是范圍(所以在這種情況下它是 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,'
您沒有使用指定要使用的輸入數量的integers
變量。
firsti
是之后的第一個輸入,但您將它用作輸入的數量和限制。 但是限制應該是 5 個數字之后的最后一個輸入。
您可以使用列表推導來刪除所有超出限制的數字。
integers = int(input())
numbers = [int(input()) for _ in range(integers)]
limit = int(input())
result = [x for x in numbers if x < limit]
print(result)
這是一個解決方案。 問題是當您使用 remove() 時,列表丟失了部分索引。
numbers=[5, 50 ,60, 140 ,3000 ,75, 100]
#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]
new_list = []
for number in numbers:
if number < lastdigi: #removes all numbers >= last digi
new_list.append(number) # [HERE] you are loosing the index
break #and prints the rest
# this whole section is to try and print the numbers from the list
for i in new_list: #and match the example output
print (i, end=',')
print(new_list)
我做了一些修改。
與 Python 中的大多數謎題一樣——列表推導往往有很大幫助,這里有一個我認為主要符合您設置的規則的示例:
data_in = '5 50 60 140 3000 75 100'
# Try cleaning the user input first, turning it to integers:
try:
values = [int(x) for x in data_in.split()]
except ValueError:
print("Only integers expected")
# Check rules set are adhered to:
# in theory could user input could at min be two integers "0 100"
if len(values) < 2:
raise ValueError('Need to at minimum specify a length and max value')
elif len(values) - 2 != values[0]:
raise ValueError('First value should be count of expected ints')
# remove first and last entry-- then filter based on last value.
results = [x for x in values[1:-1] if x < values[-1]]
# Pretty the output with commas:
print(",".join([str(x) for x in results]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.