开发者

using remove on nested lists

开发者 https://www.devze.com 2023-01-03 06:57 出处:网络
n=[[\'dgd\',\'sd\',\'g开发者_Python百科sg\'],[\'fsdsdf\',\'sds\',\'sdf\']] >>> n.remove(\'sd\')
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

精彩评论

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