【问题标题】:python removing empty objects in a arraypython删除数组中的空对象
【发布时间】: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


【解决方案1】:

你可以使用:

array = [{'hsp': 24, 'lsp': 22, 'timefrom': '00:00', 'timeto': '23:59'}, {}, {}, {}]
edited_array = [x for x in array if x]
print(edited_array)

输出

[{'hsp': 24, 'lsp': 22, 'timefrom': '00:00', 'timeto': '23:59'}]

在 Python 中,空字典 {} 和空列表 [] 的计算结果为 False。上述列表推导将array 中的每一项添加到edited_array,如果它不是False(即不为空)。

【讨论】:

猜你喜欢
  • 2015-12-24
  • 2016-11-26
  • 2019-09-15
  • 2021-11-17
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 2016-02-26
相关资源
最近更新 更多