python - 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.
解决方案
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!
...
推荐阅读
- json - 如何从 Splunk 中的 Json 字符串中提取键值字段
- sql - 列子集的 SQL 平均值
- c# - 使用 INotifyPropertyChanged 而不是 ObservableCollection
- python - 使用参数作为 scipy.optimize.curve_fit 的界限
- arrays - 用另一个数组过滤一个对象数组 - 返回两个值
- flutter - 在颤动中使用用户输入(行和列)创建 Gridview
- javascript - 在外部单击时关闭多个框下拉菜单
- android - 将 Android.mk 转换为 android.bp 时出错
- java - 编译时找不到 Manifest.permission.CAPTURE_VIDEO_OUTPUT,如何解决?
- javascript - 未捕获的类型错误:无法设置未定义的属性“值” // for 和 while 循环的区别?