鱼C论坛

 找回密码
 立即注册
查看: 1802|回复: 3

list

[复制链接]
发表于 2023-8-13 16:41:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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]
output11.append([i])
print(output11)

得到:[None, [6]]
我不知道为什么?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-8-13 16:41:35 | 显示全部楼层
你的答案中有一个小错误,sort()方法是原地排序,它返回的是None,而不是排序后的列表。所以你在将排序结果赋值给output11时,实际上是将None赋值给了它。

正确的做法是先将列表中大于0的元素取出来,然后对剩余的元素进行排序,最后将两个列表组成一个新的列表。

下面是正确的代码:
q11_list = [-1, -2, -3, -4, -5, 6, -7, -8, -9, -10]

output11 = []
output11.append(sorted([x for x in q11_list if x < 0]))
output11.append(sorted([x for x in q11_list if x > 0]))

print(output11)

这段代码首先通过列表推导式分别筛选出小于0和大于0的元素,然后使用sorted()函数对它们进行排序。最后将两个排序后的列表作为元素添加到output11中,并打印结果。

输出结果应该是:
[[-10, -9, -8, -7, -5, -4, -3, -2, -1], [6]]
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-13 16:41:58 | 显示全部楼层
你的代码有一些问题,导致输出不符合预期。问题在于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([num for num in q11_list if num < 0]))
output11.append(sorted([num for num in q11_list if num > 0]))

print(output11)

输出结果为:
[[-10, -9, -8, -7, -5, -4, -3, -2, -1], [6]]

修正后的代码使用了列表推导式和条件判断来筛选出小于0和大于0的数字,并使用sorted()方法对它们进行排序。最后,将两个列表分别添加到output11中。
如果问题已经解决,请设置最佳答案
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-13 17:07:09 | 显示全部楼层
sort()方法会直接在列表里进行排序,不会返回排序好的列表,因此返回值为None。
下面是修改后的代码:
i = q11_list.pop(5)
q11_list.sort()
output11 = [q11_list,[i]]
print(output11)
输出为:[[-10, -9, -8, -7, -5, -4, -3, -2, -1], [6]]
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 22:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表