【问题标题】:Python: Looping over all the lists in a dictionary simultaneously in order to filter out elementsPython:同时循环遍历字典中的所有列表以过滤掉元素
【发布时间】: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


【解决方案1】:

您可以找到一个“禁止”索引列表,然后可以使用这些索引来过滤结构:

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()}

输出:

{'foo1': [4, 7, -2], 'foo2': [2, 5, 6], 'foo3': [2, 3, 5]}

【讨论】:

  • 请注意 Python 初学者(像我一样)set comprehensions 用于创建 new_dict(如果你想用谷歌搜索的话)
  • 哦,还有dictionary comprehensions
【解决方案2】:

这是一个厚颜无耻的单行:

>>> dict(zip(someDict, map(list, zip(*(ts for ts in zip(*someDict.values()) if all(ts))))))
{'foo3': [2, 3, 5], 'foo1': [4, 7, -2], 'foo2': [2, 5, 6]}
>>>

【讨论】:

    【解决方案3】:

    original_dict 的其他选项,更详细且更具破坏性 (pop):

    some_dict = {
        'foo1': [1, 0, 2, 3, -2],
        'foo2': [0, 2, 5, 3, 6],
        'foo3': [1, 2, 3, 0, 5]
    }
    
    for k, v in some_dict.items():
      id = []
      for i, e in enumerate(v):
        if e == 0: id.append(i-len(id))
      [ [ some_dict[k].pop(x) for x in id ] for k,v in some_dict.items() ]
    
    print(some_dict)
    #=> {'foo1': [2, -2], 'foo2': [5, 6], 'foo3': [3, 5]}
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-27
    • 2015-10-30
    • 2019-07-10
    • 2019-03-22
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多