开发者

How to delete an inner element from a nested list in Python?

开发者 https://www.devze.com 2022-12-16 19:21 出处:网络
I have created a list a = [[3,开发者_开发百科 4], [5], [6, 7, 8]] I want to delete 3 from this list. What is the command for this?lots of possible ways

I have created a list

a = [[3,开发者_开发百科 4], [5], [6, 7, 8]]

I want to delete 3 from this list. What is the command for this?


lots of possible ways

>>> mylist = [[3,4],[5],[6,7,8]]
>>> mylist[0] = [4]
>>> mylist
[[4], [5], [6, 7, 8]]
>>> mylist = [[3,4],[5],[6,7,8]]
>>> del mylist[0][0]
>>> mylist
[[4], [5], [6, 7, 8]]
>>> mylist = [[3,4],[5],[6,7,8]]
>>> mylist[0].remove(3)
>>> mylist
[[4], [5], [6, 7, 8]]

Take your pick :)


Easy, you can try this

del a[0][0]


Assuming, you want to delete all 3s from a list of lists:

>>> lst = [[3,4],[5],[6,7,8]]
>>> [[i for i in el if i != 3] for el in lst]
[[4], [5], [6, 7, 8]]


a[0].remove(3)

(had to add more text so it was long enough)


Using this:

del a[0][0]

For a better understanding of lists, dictionaries, etc., I suggest you should read Dive Into Python You'll find Chapter 3 very useful.


if you don't know where "3" is,

>>> for n,i in enumerate(list):
...   if 3 in i: list[n].remove(3)
...
>>> list
[[4], [5], [6, 7, 8]]
>>>


First of all, be careful because you are shadowing the built in name "list". This

a_list = [[3,4],[5],[6,7,3, 3, 8]]

def clear_list_from_item(a_list, item):
   try:
       while True: a_list.remove(item)
   except ValueError:
       return a_list

a_list = [clear_list_from_item(x, 3) for x in a_list]

This will modify your original list in place.


If I understand your question you have list in a list and you want to delete first element from first list. So use:

del a[0][0]


two easy ways to remove from a list, if you know the element of concern is at position 0:

a[0].pop (0)
del a[0][0]
0

精彩评论

暂无评论...
验证码 换一张
取 消