请教Python里面不用sort()进行排序的方法

Gao - not understood 2019-06-17 05:51:11
一个Python小白,在老师布置的题目中晕晕乎乎地写了一堆代码,到后面发现有sort函数,但是快打完发现没用sort也可以做出来,就是有一个问题,请看截图: 怎么解决呢?
...全文
1444 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
pyhoho 2019-06-25
  • 打赏
  • 举报
回复
[code=python]list2 = [91, 95, 97, 99, 100]
list1 = [92, 93, 96, 98, 101, 102, 105, 109]

len1 = len(list1)
len2 = len(list2)

print(len1, len2)
list3 = []
if len1 < len2:
for a in range(len1):
if list1[a] < list2[a]:
list3.append(list1[a])
list3.append(list2[a])
else:
list3.append(list2[a])
list3.append(list1[a])
list3 = list3 +list2[len1:len2]
else:
for a in range(len2):
if list1[a] < list2[a]:
list3.append(list1[a])
list3.append(list2[a])
else:
list3.append(list2[a])
list3.append(list1[a])
list3 = list3 +list1[len2:len1]
print(list3)
[/code

不知道這樣行不行?
  • 打赏
  • 举报
回复
我试了一下,还是不行呐。改了以后只对list1排序了。
一笑程序猴 2019-06-17
  • 打赏
  • 举报
回复
不是因为当list2有比list1大的元素的时候就会报错,而是索引越界。把order += 1放在for循环中的最后就好了

list1 =  [91, 95, 97, 99, 100]  
list2 =  [92, 93, 96, 98, 101, 102, 105, 109]
list3 = []
if list1[0] >= list2[0]:
    list3.append(list2[0])
else:
    list3.append(list1[0])
order = 0
for score1 in list1:
    for score2 in list2:
        if score2 >= score1 and score2 <= list1[order]:
        	list3.append(score2)
    if order <= len(list1)-1:
    	list3.append(list1[order])
    
    order += 1
print(list3)
  • 打赏
  • 举报
回复
list1 = [91, 95, 97, 99, 100]
list2 = [92, 93, 96, 98, 101, 102, 105, 109]
list3 = []
if list1[0] >= list2[0]:
list3.append(list2[0])
else:
list3.append(list1[0])
order = 0
for score1 in list1:
order += 1
for score2 in list2:
if score2 >= score1 and score2 <= list1[order]:
list3.append(score2)
if order <= len(list1)-1:
list3.append(list1[order])
print(list3)

#当list2有比list1大的元素的时候,会报错

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧