简体   繁体   English

Python:按索引删除列表中的项目

[英]Python: Remove items in list of list by index

Here i want remove items in list of list by index. 在这里我想按索引删除列表中的项目。 Input is 输入为

li  = [[1,2,3,4],[5,6,7,8]]

Excepted output is 排除的输出是

[[1,3,4],[5,7,8]]

What I'm tried is, 我尝试过的是

print [x.pop(1) for x in li]

You can use the del operator like this: 您可以像这样使用del运算符:

for sublist in list:
    del sublist[1]

You actually removed the items in the given index but you printed out the wrong list. 您实际上删除了给定索引中的项目,但打印出了错误的列表。 Just print li after you pop the items: 弹出项目后只需打印li

>>> [x.pop(1) for x in li]
>>> print li

However, do you really have to use list comprehensions? 但是,您真的必须使用列表推导吗? Because calling .pop() in a list comprehension will accumulate the removed items and creates a new, totally useless list with them. 因为在列表.pop()调用.pop()会累积删除的项并与它们一起创建一个新的,完全无用的列表。

Instead, you can just do the following: 相反,您可以执行以下操作:

>>> for lst in li:
...    lst.pop(1)   

pop , like del change the underlying list so you must explicitely loop through the sublists to remove second element and them print the modified list. pop ,就像del一样,更改基础列表,因此您必须显式循环遍历子列表以删除第二个元素,并且它们将显示修改后的列表。

for l in li: del l[1]
print li

If on the other hand, you do not want to change the lists but directly print the result, you could use a list comprehension: 另一方面,如果您不想更改列表,而是直接打印结果,则可以使用列表理解:

print [ (l[:1] + l[2:]) for l in li ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM