list
Starting with the following list.-1, -2, -3, -4, -5, 6, -7, -8, -9, -10
Write a Python program to transform the list above a list with two elements, each containing a list. The first element, should contain all numbers less than 0 in ascending order, while the second should contain all elements greater than 0 in ascending order. You must do this exclusively using list methods. Create a variable output11 and assign the solution to it.
Use the list operations sort(), pop() and append() to perform this.
我的答案:
i = q11_list.pop(5)
output11 = q11_list.sort()
output11 =
output11.append()
print(output11)
得到:]
我不知道为什么? 你的答案中有一个小错误,sort()方法是原地排序,它返回的是None,而不是排序后的列表。所以你在将排序结果赋值给output11时,实际上是将None赋值给了它。
正确的做法是先将列表中大于0的元素取出来,然后对剩余的元素进行排序,最后将两个列表组成一个新的列表。
下面是正确的代码:
q11_list = [-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]
output11 = []
output11.append(sorted())
output11.append(sorted())
print(output11)
这段代码首先通过列表推导式分别筛选出小于0和大于0的元素,然后使用sorted()函数对它们进行排序。最后将两个排序后的列表作为元素添加到output11中,并打印结果。
输出结果应该是:
[[-10, -9, -8, -7, -5, -4, -3, -2, -1], ]
你的代码有一些问题,导致输出不符合预期。问题在于sort()方法会原地排序列表,并且返回值为None,而不是排序后的列表。因此,在你的代码中,output11 = q11_list.sort()会将output11赋值为None。另外,你应该先创建一个空列表作为output11,然后使用append()方法逐步添加元素。
以下是修正后的代码:
q11_list = [-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]
output11 = []
output11.append(sorted())
output11.append(sorted())
print(output11)
输出结果为:
[[-10, -9, -8, -7, -5, -4, -3, -2, -1], ]
修正后的代码使用了列表推导式和条件判断来筛选出小于0和大于0的数字,并使用sorted()方法对它们进行排序。最后,将两个列表分别添加到output11中。
如果问题已经解决,请设置最佳答案 sort()方法会直接在列表里进行排序,不会返回排序好的列表,因此返回值为None。
下面是修改后的代码:
i = q11_list.pop(5)
q11_list.sort()
output11 = ]
print(output11)
输出为:[[-10, -9, -8, -7, -5, -4, -3, -2, -1], ]
页:
[1]