【问题标题】:How do you remove numbers greater than or equal to a specified number within a list, in python如何在python中删除列表中大于或等于指定数字的数字
【发布时间】: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


【解决方案1】:

您没有使用指定要使用的输入数量的integers 变量。

firsti 是之后的第一个输入,但您将它用作输入的数量和限制。但是限制应该是 5 个数字之后的 last 输入。

您可以使用列表推导来删除所有超出限制的数字。

integers = int(input())
numbers = [int(input()) for _ in range(integers)]
limit = int(input())

result = [x for x in numbers if x < limit]
print(result)

【讨论】:

    【解决方案2】:

    这里有一个解决方案。 问题是当您使用 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)
    
    

    我做了一些修改。

    【讨论】:

      【解决方案3】:

      与 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]))
      

      【讨论】:

        猜你喜欢
        • 2019-12-25
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 2014-12-20
        • 2023-03-21
        相关资源
        最近更新 更多