书中示例
# -*- coding: utf-8 -*-
# Author: 桑葚ICE
# Email: 152516cc@gmail.com
# Blog: iicey.github.io
# JueJin: juejin.im/user/5c64dce8e51d45013c40742c
arr1 = [1, 3, 4, 6, 10] # 初始化两个数组
arr2 = [2, 5, 8, 11]
ind = 0
ans = arr1.copy() # ans初始化为arr1
for i in range(0, len(arr2)):
while ind < len(arr1):
if arr2[i] <= arr1[ind]: # ind的范围不能超过数组元素下标的最大值
ans.insert(ind + i, arr2[i]) # 向第一个数组中的合适位置插入第二个数组的数
break
else:
ind += 1 # 如果ind指向的数比i指向的数小,则ind向后一位
else: # 如果arr1已遍历完,直接把剩下的arr2拼到arr1结尾
ans = ans + arr2[i:]
break
print(ans)
其它示例
enumerate
# -*- coding: utf-8 -*-
# Author: 桑葚ICE
# Email: 152516cc@gmail.com
# Blog: iicey.github.io
# JueJin: juejin.im/user/5c64dce8e51d45013c40742c
arr1 = [1, 3, 4, 6, 10]
arr2 = [2, 5, 8, 11]
for element_2 in arr2:
for index_1, element_1 in enumerate(arr1):
if element_2 < element_1:
arr1.insert(index_1, element_2)
break
print(arr1)
sort
# -*- coding: utf-8 -*-
# Author: 桑葚ICE
# Email: 152516cc@gmail.com
# Blog: iicey.github.io
# JueJin: juejin.im/user/5c64dce8e51d45013c40742c
arr1 = [1, 3, 4, 6, 10]
arr2 = [2, 5, 8, 11]
arr1.extend(arr2)
arr1.sort()
print(arr1)