python第一行输入一个列表 第二行输入一个整数,记为n 删除列表中第n个元素,这里n是下标 输出删除后的列表 n可以是负数; n超过列表范围,则不删除
时间: 2024-02-29 14:51:24 浏览: 95
好的,可以使用如下代码实现:
```python
lst = input().split() # 输入列表
n = int(input()) # 输入删除元素的下标
if n >= len(lst) or n < -len(lst): # 如果下标超出范围,不删除
print(lst)
elif n >= 0: # 如果下标为正数,直接删除
del lst[n]
print(lst)
else: # 如果下标为负数,需要转化为正数再删除
del lst[n + len(lst)]
print(lst)
```
其中,`input().split()` 会将输入的一行字符串按空格分隔为一个列表,`int(input())` 则会将输入的字符串转化为整数。如果下标超出列表范围,则直接输出原列表;如果下标在范围内,则使用 `del` 删除对应元素。需要注意的是,对于负数下标,需要将其转化为正数再进行删除。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)