【发布时间】:2018-12-11 19:56:22
【问题描述】:
我有一些字典
someDict = {
'foo1': [1, 4, 7, 0, -2],
'foo2': [0, 2, 5, 3, 6],
'foo3': [1, 2, 3, 4, 5]
}
我想用 Python 3 遍历每个列表中的所有元素,当某个给定索引处的元素为零时,我想为 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)
【问题讨论】:
-
如果
'foo1': [0, 4, 7, 1, -2]和'foo2': [2, 0, 5, 3, 6]应该先删除foo2的第一个元素会发生什么? -
@MarkMeyer,如果有意义的话,我想以
'foo1': [7, 1, -2]和'foo2': [5, 3, 6]结尾
标签: python python-3.x list dictionary