给定一个字典,其中列表为值和单独的列表:
myDict = {0: [0, 1, 2], 1: [], 2: [20, 25, 26, 28, 31, 34], 3: [], 4: [0, 1, 2, 3, 4, 7, 10], 5: [], 6: [10, 20, 24]}
myList = [1, 34, 10]
如果myDict中的值与myList中的值匹配,如何从myDict中的列表中删除值?
因此,对于示例字典,我最终期望这样的字典:
myDict = {0: [0, 2], 1: [], 2: [20, 25, 26, 28, 31], 3: [], 4: [0, 2, 3, 4, 7], 5: [], 6: [20, 24]}
答案 0 :(得分:3)
使myList
成为一组,并使用dict和list comprehension组合:
mySet = set(myList)
myDict = {k: [i for i in v if i not in mySet] for k, v in myDict.items()}
使用集合可以提高效率,因为in
成员资格测试对于集合而言比对列表要快得多。
答案 1 :(得分:2)
这有效:
>>> myDict = {0: [0, 1, 2], 1: [], 2: [20, 25, 26, 28, 31, 34], 3: [], 4: [0, 1, 2, 3, 4, 7, 10], 5: [], 6: [10, 20, 24]}
>>> myList = [1, 34, 10]
>>> {x:[z for z in y if z not in myList] for x,y in myDict.items()}
{0: [0, 2], 1: [], 2: [20, 25, 26, 28, 31], 3: [], 4: [0, 2, 3, 4, 7], 5: [], 6: [20, 24]}
>>>
答案 2 :(得分:0)
这个答案也有效:
updatedDict = {k:list(set(v) - set(myList)) for k, v in myDict.items()}