码迷,mamicode.com
首页 > 编程语言 > 详细

[Python3] 021 关于列表中“换位”的一些发现

时间:2019-03-05 21:35:17      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:tar   文章   目标   thread   https   .com   http   最大值   论坛   

关于列表中“换位”的一些发现

“缘起”

先放代码

代码 (1)

  • 目标:列表首位不是最大值时,找到最大值并与列表首位的数据交换位置
num_list = [1, 3, 5, 66, 7, 9]
print("排序前:", num_list)

num_max = max(num_list)             # 找到最大值
max_idx = num_list.index(num_max)       # 找到最大值的索引值
num_list[0], num_list[max_idx] = num_list[max_idx], num_list[0]

print("排序后:", num_list)

>>>
排序前: [1, 3, 5, 66, 7, 9]
排序后: [66, 3, 5, 1, 7, 9]

  • 结果:交换成功

代码 (2)

  • 目标:缩减代码 (1)
num_list = [1, 3, 5, 66, 7, 9]
print("排序前:", num_list)

num_max = max(num_list)
num_list[0], num_list[num_list.index(num_max)] = num_list[num_list.index(num_max)], num_list[0]

print("排序后:", num_list)

>>>
排序前: [1, 3, 5, 66, 7, 9]
排序后: [1, 3, 5, 66, 7, 9]

  • 结果:出现问题!代码 (2) 没效果!

代码 (3)

  • 目标:看看最小值与末位交换的情况
num_list = [1, 3, 5, 66, 7, 9]
print("排序前:", num_list)

num_min = min(num_list)
num_list[-1], num_list[num_list.index(num_min)] = num_list[num_list.index(num_min)], num_list[-1]

print("排序后:", num_list)

>>>
排序前: [1, 3, 5, 66, 7, 9]
排序后: [9, 3, 5, 66, 7, 1]

  • 结果:最小值与末位互换位置成功

代码 (4-1)

  • 将 num_list 中的 66 与其前面的数据互换位置
num_list = [1, 3, 5, 66, 7, 9]
print("排序前:", num_list)

num_max = max(num_list)
num_list[2], num_list[num_list.index(num_max)] = num_list[num_list.index(num_max)], num_list[2]

print("排序后:", num_list)

>>>
排序前: [1, 3, 5, 66, 7, 9]
排序后: [1, 3, 5, 66, 7, 9]

  • 结果:66 与 5 换位失败
  • 经检验,66 与其前面的 3 个数据均不能互换位置

代码 (4-2)

  • 将 num_list 中的 66 与其后面的数据互换位置
num_list = [1, 3, 5, 66, 7, 9]
print("排序前:", num_list)

num_max = max(num_list)
num_list[4], num_list[num_list.index(num_max)] = num_list[num_list.index(num_max)], num_list[4]

print("排序后:", num_list)

>>>
排序前: [1, 3, 5, 66, 7, 9]
排序后: [1, 3, 5, 7, 66, 9]

  • 结果:66 与 7 换位成功
  • 经检验,66 与其后面的数据均能互换位置

代码 (5)

  • 我的想法:之前一直在索引值上做文章,摆放位置有没有影响?
num_list = [1, 3, 5, 66, 7, 9]
print("排序前:", num_list)

num_max = max(num_list)
num_list[num_list.index(num_max)], num_list[0] = num_list[0], num_list[num_list.index(num_max)]

print("排序后:", num_list)

>>>
排序前: [1, 3, 5, 66, 7, 9]
排序后: [66, 3, 5, 1, 7, 9]

  • 结论:代码 (5) 与代码 (2) 仅在 x, y = y, x 的顺序上有不同,但结果却大相径庭

后记

  • 解法是知道了,但原因我还不知道,所以又到了挖坑的时间
    • 坑号编码:Py021-1

[Python3] 021 关于列表中“换位”的一些发现

标签:tar   文章   目标   thread   https   .com   http   最大值   论坛   

原文地址:https://www.cnblogs.com/yorkyu/p/10479638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!