如果所有值都是空字符串,则从列表中删除dictionaire

2024-09-29 23:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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:''}]

欢迎任何帮助!你知道吗


Tags: 列表key2key1ggkey3jj个键dictionaire
2条回答

使用列表理解和any()

[d for d in inputlist if any(d.itervalues())]

在python3中使用any(d.values())。你知道吗

any()仅当输入列表中有任何非空值时返回True。通过使用d.itervalues(),我们测试字典中的最小值数,以证明它们之间存在一个非空值。你知道吗

演示:

>>> inputlist = [{'Key1': 'JJ', 'Key2': 'GG', 'Key3':''}, {'Key1': '', 'Key2': '', 'Key3': ''}, {'Key1': '', 'Key2': 'GG', 'Key3': ''}, {'Key1': '', 'Key2': '', 'Key3': ''}]
>>> [d for d in inputlist if any(d.itervalues())]
[{'Key3': '', 'Key2': 'GG', 'Key1': 'JJ'}, {'Key3': '', 'Key2': 'GG', 'Key1': ''}]

如果除空字符串以外的任何值也可以测试为false(例如None0),那么也可以使用显式测试:

[d for d in inputlist if any(v != '' for v in d.itervalues())]

使用list comprehension根据^{}*返回的内容筛选键:

>>> dct = [{'Key1':'JJ', 'Key2':'GG', 'Key3':''},{'Key1':'', 'Key2':'', 'Key3':''},{'Key1':'',
'Key2':'GG', 'Key3':''},{'Key1':'', 'Key2':'', 'Key3':''}]
>>> [x for x in dct if any(y != '' for y in x.values())]
[{'Key3': '', 'Key2': 'GG', 'Key1': 'JJ'}, {'Key3': '', 'Key2': 'GG', 'Key1': ''}]
>>>

或者,如果值都是字符串,则可以执行以下操作:

>>> dct = [{'Key1':'JJ', 'Key2':'GG', 'Key3':''},{'Key1':'', 'Key2':'', 'Key3':''},{'Key1':'',
'Key2':'GG', 'Key3':''},{'Key1':'', 'Key2':'', 'Key3':''}]
>>> [x for x in dct if any(x.values())]
[{'Key3': '', 'Key2': 'GG', 'Key1': 'JJ'}, {'Key3': '', 'Key2': 'GG', 'Key1': ''}]
>>>

这是因为在Python中空字符串的计算结果是False。你知道吗


*注意:如果您使用的是python2.x,那么应该使用^{}代替dict.values。它更有效,因为它返回一个迭代器而不是一个列表。你知道吗

相关问题 更多 >

    热门问题