Python:同时循环遍历字典中的所有列表以过滤掉元素

Hun*_*ter 2 python dictionary list python-3.x

我有一些字典

someDict = {
    'foo1': [1, 4, 7, 0, -2],
    'foo2': [0, 2, 5, 3, 6],
    'foo3': [1, 2, 3, 4, 5]
}
Run Code Online (Sandbox Code Playgroud)

我想用Python 3遍历每个列表中的所有元素,当某个给定索引处的元素等于零时,我想在该索引中删除该字典中所有列表/属性的元素.所以字典最终成为

someDict = {
    'foo1': [4, 7, -2],
    'foo2': [2, 5, 6],
    'foo3': [2, 3, 5]
}
Run Code Online (Sandbox Code Playgroud)

请注意,我事先不知道字典会有多少个键/列表,我不知道列表中包含多少个元素.我已经提出了以下代码,这似乎有效,但是想知道是否有更有效的方法来做到这一点?

keyPropList = someDict.items()
totalList = []

for tupleElement in keyPropList:
    totalList.append(tupleElement[1])

copyTotalList = totalList[:]
for outerRow in copyTotalList:
    for outerIndex, outerElement in enumerate(outerRow):
        if outerElement==0:
            for innerIndex, _ in enumerate(copyTotalList):
                del totalList[innerIndex][outerIndex]

print('someDict =', someDict)
Run Code Online (Sandbox Code Playgroud)

Aja*_*234 8

您可以找到"禁用"索引列表,然后可以使用这些索引来过滤结构:

someDict = {
  'foo1': [1, 4, 7, 0, -2],
  'foo2': [0, 2, 5, 3, 6],
  'foo3': [1, 2, 3, 4, 5]
}
results = {i for c in someDict.values() for i, a in enumerate(c) if not a}
new_dict = {a:[c for i, c in enumerate(b) if i not in results] for a, b in someDict.items()}
Run Code Online (Sandbox Code Playgroud)

输出:

{'foo1': [4, 7, -2], 'foo2': [2, 5, 6], 'foo3': [2, 3, 5]}
Run Code Online (Sandbox Code Playgroud)