【问题标题】:Filter and sort a List过滤和排序列表
【发布时间】:2023-04-04 16:09:01
【问题描述】:

过滤和排序列表 编写一个程序,从输入中获取整数列表,并按升序(从低到高)输出非负整数。

例如:如果输入是:

10 -7 4 39 -6 12 2

输出是:

2 4 10 12 39

为简化编码,在每个输出值后面加一个空格。不要以换行符结尾。

我已经尝试并在第 7 行提出了一个 TypeError。我已经尝试了所有方法来修复它。提示或帮助将不胜感激。花了几个小时试图弄清楚如何修复错误,所以 zybooks 接受了答案。

这是我的代码。

# asking for user input

       nums = input()

        lst = nums.split() # user input splits
# starting of a new list
new_list = ([])
for i in lst:  # for loop to see if i in lst is true
    if int(i) > 0: # if loop to see it integer is greater than 0  <--- This is where my error is
    
new_list.append(int(i)) # adding integers to the end
new_list.sort() # sorting new list in order, lowest to largest
for x in new_list: # seeing if x is true in the new list
   print(x, end=' ') # printing new list in new order

我收到的错误是:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    if int(i) > 0: # if loop to see it integer is greater than 0 
ValueError: invalid literal for int() with base 10: '10,'

【问题讨论】:

  • 请使用完整的错误回溯更新您的问题。
  • 这是我得到的错误。回溯(最近一次调用最后一次):文件“main.py”,第 10 行,在 中 if int(i) > 0: # if loop to see it integer is greater than 0 ValueError: invalid literal for int() with基数 10: '10,'
  • 另外,第一次在这里发帖。对压痕感到抱歉。这不是问题。谢谢。
  • 您的意思是:lst = nums.split(',')?还是您的意思是让用户输入以空格分隔的数字?
  • if int(i) > 0: 那是代码给我带来麻烦的部分

标签: python list sorting filter


【解决方案1】:

您很可能面临缩进错误。我已将您的代码编辑为适当的缩进试试这个 -

nums = input()
lst = nums.split()

new_list = []

for i in lst:  # for loop to see if i in lst is true
    if int(i) > 0:
        new_list.append(int(i)) # adding integers to the end

new_list.sort() # sorting new list in order, lowest to largest

for x in new_list: # seeing if x is true in the new list
    print(x, end=' ') # printing new list in new order
10 -7 4 39 -6 12 2

2 4 10 12 39 

这是使用单行代码list comprehension 执行此操作的一种更简洁的方法。

out = sorted([int(i) for i in input().split() if int(i)>0])
print(out)
10 -7 4 39 -6 12 2

[2, 4, 10, 12, 39]

【讨论】:

    【解决方案2】:

    除了缩进问题,您可以考虑使用列表推导以更 Python 的方式解决问题 :)

    def filter_and_sort(nums):
      """Returns a sorted 'list' of `nums`, only considering any `num > 0`."""
      return sorted(num for num in nums if num > 0)
    
    # read user input, `strip()` whitespace and `split()` on space,
    # and cast each entry to an int
    input_numbers = map(int, input().strip().split())
    
    sorted_numbers = filter_and_sort(input_numbers)
    
    # map each number into a string, then join strings using a space, and print to screen.
    print(" ".join(map(str, sorted_numbers))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      相关资源
      最近更新 更多