简体   繁体   中英

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:

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:

>>> [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.

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.

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 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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