我有一个dictionaires列表(列表中的所有dictionaires都有相同的9个键),我想删除列表中9个键的值为“”的dictionaires。但如果至少有一个键有一个值,它将保留整个dictionaire(包括它所在的其他键)
例如(只有3个键需要简化)
[{Key1:JJ, Key2:GG, Key3:''},{Key1:'', Key2:'', Key3:''},{Key1:'', Key2:GG, Key3:''},{Key1:'', Key2:'', Key3:''}]
输出将是
[{Key1:JJ, Key2:GG, Key3:''},{Key1:'', Key2:GG, Key3:''}]
欢迎任何帮助!你知道吗
使用列表理解和
any()
:在python3中使用
any(d.values())
。你知道吗any()
仅当输入列表中有任何非空值时返回True
。通过使用d.itervalues()
,我们测试字典中的最小值数,以证明它们之间存在一个非空值。你知道吗演示:
如果除空字符串以外的任何值也可以测试为false(例如
None
或0
),那么也可以使用显式测试:使用list comprehension根据^{} *返回的内容筛选键:
或者,如果值都是字符串,则可以执行以下操作:
这是因为在Python中空字符串的计算结果是
False
。你知道吗*注意:如果您使用的是python2.x,那么应该使用^{} 代替
dict.values
。它更有效,因为它返回一个迭代器而不是一个列表。你知道吗相关问题 更多 >
编程相关推荐