如何避免使用元组,如果没有列表理解,这将是什么样子

Web*_*ter 0 python

我应该用Python编程,我只使用Python 3周.我必须解决各种问题并将功能写成训练.对于我的一个功能,我使用这一行.

theDict = dict( [(k,v) for k,v in theDict.items() if len(v)>0])
Run Code Online (Sandbox Code Playgroud)

但是,我不能使用任何我不完全理解或无法完全解释的东西.我理解这条线的主旨,但是,我无法解释它.所以我的导师告诉我,要使用它,我必须学习有关元组的所有内容并完全理解列表理解,或者我必须在纯python中编写它.

该行基本上查看字典,并在字典内,它应该寻找等于空列表的值并删除这些键/值.

所以,我的问题是,在纯粹的非列表理解python中,这一行会是什么样子?我会尝试写它,因为我想尽我所能,这不是一个网站,你得到免费的答案,但你们纠正我,并帮助我完成它,如果它不起作用.

另一个问题是,字典"值"内的空列表,如果它们是空的,那么它们将不会在循环内处理.该循环应该删除等于空值的键.那么你应该如何检查列表是否为空,如果检查是在循环内,并且循环不会在其体内有空数组?

for key,value in TheDict.items(): #i need to add 'if value:' somewhere, 
#but i don't know how to add it to make it work, because 
#this checks if the value exists or not, but if the value 
#doesn't exist, then it won't go though this area, so 
#there is no way to see if the value exists or not. 
     theDict[key]=value
Run Code Online (Sandbox Code Playgroud)

如果有更好的方法来删除具有空列表值的字典值.请告诉我.

怎么会

theDict = dict( [(k,v) for k,v in theDict.items() if len(v)>0])
Run Code Online (Sandbox Code Playgroud)

看起来好像没有使用发电机?

cva*_*val 7

result = dict([(k,v) for k,v in theDict.items() if len(v)>0])
Run Code Online (Sandbox Code Playgroud)

看起来会像(如果你想要新词典)

result = {}
for key, value in theDict.items():
    if len(value) > 0:
        result[key] = value
Run Code Online (Sandbox Code Playgroud)

如果要修改现有字典:

for key, value in theDict.items():
    if not len(value) > 0:
        del theDict[key]
Run Code Online (Sandbox Code Playgroud)

  • 简单不是很好的例子 - 假设有一个'None`的值.这会导致异常,但在您的代码中,它将被忽略 (2认同)