首页 > 解决方案 > Proper way to iterate through a list which may not be a list

问题描述

Currently i am getting information from an xml file. If an xml tag has more then one children it will return as a list inside that tag, however if that xml tag has only 1 child it will return not as a list and only as a regular string.

My question is: is there a better way to iterate through this tag? if it is a list, iterate through the list length amount of times, but if it is a string only iterate once?

This is my current approach:

 #check if tag is a list, if not then make a list with empty slot at end
 if not isinstance(accents['ac'], list):
      accents['ac'] = list((accents['ac'], {}))

 #loop through guaranteed list
 for ac in accents['ac']: #this line throws error if not list object!

      #if the empty slot added is encountered at end, break out of loop
      if bool(ac) == False:
            break

any ideas on how to make this cleaner or more professional is appreciated.

标签: pythonpython-3.xlistiteration

解决方案


Assuming that the problem is caused by accents['ac'] being either a list of string or a single string, a simple processing could be:

 #check if tag is a list, if not then make a list with empty slot at end
 if not isinstance(accents['ac'], list):
      accents['ac'] = [ accents['ac'] ]

 #loop through guaranteed list
 for ac in accents['ac']: #this line throws error if not list object!
     ...

推荐阅读