删除列表中的第二个元素
答
你可以只使用索引妥善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
deans7请[接受](http://meta.stackexchange.com/a/5235)中任一项回答它是否帮助你解决了你的问题。 – Idos