【发布时间】:2015-09-06 18:36:15
【问题描述】:
我是 python 新手,正在玩数组并发现问题
array = [{'hsp': 24, 'lsp': 22, 'timefrom': '00:00', 'timeto': '23:59'},
{}, {}, {}]
我想删除空对象,结果应该是这样的[{'hsp': 24, 'lsp': 22, 'timefrom': '00:00', 'timeto': '23:59'}]
for day,value in array.iteritems():
if not value:
continue
print array
发现这无济于事
任何帮助将不胜感激。 提前致谢
【问题讨论】:
-
试试
newlist = [el for el in array if el]。顺便说一句:这是一个列表,而不是一个数组 -
array[:] = [d for d in array if d],这也将删除任何 Falsey 值,如 None、0 等。 -
谢谢.......谢谢你的回复
-
如果你只想删除空的可迭代对象
array[:] = [d for d in array if not isinstance(d, collections.Iterable) or d ]那么array = [{'hsp': 24, 'lsp': 22, 'timefrom': '00:00', 'timeto': '23:59'}, {}, {}, {},0, None]将变为[{'lsp': 22, 'timefrom': '00:00', 'hsp': 24, 'timeto': '23:59'}, 0, None]
标签: python arrays dictionary