我有一些字典
someDict = {
'foo1': [1, 4, 7, 0, -2],
'foo2': [0, 2, 5, 3, 6],
'foo3': [1, 2, 3, 4, 5]
}
我想用python3遍历每个列表中的所有元素,当某个给定索引处的元素等于0时,我想删除字典中列表/属性的all索引处的元素。所以这本字典最后成了
someDict = {
'foo1': [4, 7, -2],
'foo2': [2, 5, 6],
'foo3': [2, 3, 5]
}
请注意,我事先不知道字典将有多少键/列表,也不知道列表将包含多少元素。我已经想出了下面的代码,这似乎是工作,但不知道是否有一个更有效的方法来做到这一点?你知道吗
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)
您可以找到一个“禁止”索引列表,然后可用于过滤结构:
输出:
其他选项,更详细和破坏性(
pop
)对于original_dict
:下面是一句厚颜无耻的话:
相关问题 更多 >
编程相关推荐