python列表合并+排序的解决方法

在编写列表合并的代码时,遭遇了合并后的列表无法排序的问题。

a = [1,2,3,4,5]
b = [1,5,7,9]
c = a+b
print(c)
print(c.sort())
print(c.sorted())

执行结果:

[1, 2, 3, 4, 5, 1, 5, 7, 9]
None
Traceback (most recent call last):
  File "1.py", line 7, in <module>
    print(c.sorted())
AttributeError: 'list' object has no attribute 'sorted'

变量c正常显示2个列表的相加

第二个输出编程了None,这个可以理解,因为sort()是对原有列表的排序

而第三个报错,变成了列表没有sorted属性

这可就有点麻烦了,不能将合并+排序写的很简洁了。

解决方案:

a = [1,2,3,4,5]
b = [1,5,7,9]
for i in a:
	for j in b:
		if i <= j:
			b.insert(b.index(j), i)
			break
print(b)

用for循环嵌套来进行数值的比对和列表的添加

输出结果:

[1, 1, 2, 3, 4, 5, 5, 7, 9]

猜你喜欢

转载自blog.csdn.net/qq_18999357/article/details/80800740