开发者

using remove on nested lists

n=[['dgd','sd','g开发者_Python百科sg'],['fsdsdf','sds','sdf']]
>>> n.remove('sd')

if i have a nested list like above and want to remove 'sd'.how can i doing the above thing is giving an error??


n[0].remove('sd')

or

for i in n:
  try:
    i.remove('sd')
  except ValueError:
    pass


When you have nested lists you need to index the top level list to get to the child lists, only then can you use list operations on the child lists. So you need something like:

n[0].remove('sd')

The code you have is trying to remove the string : 'sd' from a list that only contains two lists: ['dgd','sd','gsg'] and ['fsdsdf','sds','sdf'].

Simply calling n.remove('sd') would work on nest lists if Python performed automatic tree recursion on nested collections which it does not.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜