删除列表中的第二个元素

问题描述:

我正在处理一些有整数列表的代码,例如list1 = [1,2,3,4,5],我想打印出1 3 4 5,所以只需打印出一个“new列表“没有第二个元素。删除列表中的第二个元素

+0

deans7请[接受](http://meta.stackexchange.com/a/5235)中任一项回答它是否帮助你解决了你的问题。 – Idos

你可以只使用索引妥善slicing(我假设你想保持原来的列表完整):

>>> list1[0:1] + list1[2:] 
[1, 3, 4, 5] 

所以一般来说跳过i元素(当包含0):

>>> list1[0:i] + list1[i+1:] 

更具扩展性的解决方案是提供您想要排除的原始列表的索引位置。然后enumerate覆盖该列表并排除相关索引位置处的值。

list1 = [1, 2, 3, 4, 5] 
excluded_index = [1] 
new_list = [i for n, i in enumerate(list1) if n not in excluded_index] 
>>> new_list 
[1, 3, 4, 5] 

excluded_index = [1, 3] 
>>> [i for n, i in enumerate(list1) if n not in excluded_index] 
[1, 3, 5] 

使用德尔,并指定要删除与索引的元素:

del [index]

del list1[1];将打印1 3 4 5

**注:del,将从列表中删除元素,所以如果您认为您需要完整列表以备将来使用,请小心。

删除第二个元素可以通过数组切片完成。然后使用连接字符串方法。

removed = list1[0:1] + list1[2:] 
print(' '.join([str(x) for x in removed])) 

你可以做一个简单的弹出操作,它是Python中的空格。

>>list1.pop(1) 
>>[1, 3, 4, 5] 

它将导致[1,3,4,5]将被存储在列表1