主程序中已有一个排好序的列表,请编写函数 insertList ,将从键盘接收的整数按原来从小到大的排序规律插入到该列表中。
def insertList(L1,x):
#函数代码
L1=[1,4,6,9,13,16,28,40,100]
x=int(input(' 请输入一个要插入的整数: '))
insertList(L1,x)
print(L1)
一、思路:
主要考查list的方法,比如插入。
二、代码:
def insertList(L1, x):
if x > L1[len(L1)-1]:
L1.append(x)
for i in range(0, len(L1)):
if x < L1[i]:
L1.insert(i, x) # 这就是list的舒服,直接可以插入指定序号前,不用考虑移位等等
break
return
L1 = [1, 4, 6, 9, 13, 16, 28, 40, 100]
x = int(input(' 请输入一个要插入的整数: '))
insertList(L1, x)
print(L1)
三、输出:
请输入一个要插入的整数: 101
[1, 4, 6, 9, 13, 16, 28, 40, 100, 101]
请输入一个要插入的整数: 2
[1, 2, 4, 6, 9, 13, 16, 28, 40, 100]