题解 | 【模板】序列操作
【模板】序列操作
https://www.nowcoder.com/practice/12da4185c0bb45918cfdc3072e544069
num_sequence = []
q = int(input())
for _ in range(q):
operation = input().split()
op_type = int(operation[0])
if op_type == 1:
# 操作1:向序列末尾添加整数x
x = int(operation[1])
num_sequence.append(x)
elif op_type == 2:
# 操作2:删除序列末尾的元素(保证序列非空)
num_sequence.pop()
elif op_type == 3:
# 操作3:输出下标为i的元素
i = int(operation[1])
print(num_sequence[i])
elif op_type == 4:
# 操作4:在下标i和i+1之间插入整数x
i = int(operation[1])
x = int(operation[2])
# list.insert(index, value) 会在指定下标前插入元素,正好满足题目要求
num_sequence.insert(i + 1, x)
elif op_type == 5:
# 操作5:序列升序排序(直接修改原列表)
num_sequence.sort()
elif op_type == 6:
# 操作6:序列降序排序(直接修改原列表)
num_sequence.sort(reverse=True)
elif op_type == 7:
# 操作7:输出当前序列的长度
print(len(num_sequence))
elif op_type == 8:
# 操作8:输出整个序列,元素之间用空格分隔
# 先将所有整数转为字符串,再用join方法拼接
print(" ".join(map(str, num_sequence)))
查看1道真题和解析