【问题标题】:Deleting an item from a list which is a value in a given dictionary从列表中删除一个给定字典中的值的项目
【发布时间】:2021-04-04 17:42:45
【问题描述】:
myDict={0:[1,2,3,4],1:[0,2],2:[0,1],3:[0,4],4:[0,3]}

您好,对于字典的概念,我不知道如何从任何键值对的列表中删除一个项目。假设我在 myDict[0] 上,我关心的是如何删除让我们说 0:[1,2,3,4] 列表的值 1 和 2。谢谢!

【问题讨论】:

    标签: python-3.x list dictionary key-value


    【解决方案1】:
    myDict = {0: [1, 2, 3, 4], 1: [0, 2], 2: [0, 1], 3: [0, 4], 4: [0, 3]}
    
    myDict[0] = [3, 4]  # Whatever here
    '''
    You can treat myDict[0] as a normal list
    '''
    myDict[0].remove(3)  # Same as list.remove(), because myDict[0] is just a list
    print(myDict[0])
    print(myDict[0][0])# Printing the 0th value in the list, which is myDict[0]
    

    【讨论】:

    • 知道了!谢谢你:)
    【解决方案2】:
    myDict = {0: [1, 2, 3, 4], 1: [0, 2], 2: [0, 1], 3: [0, 4], 4: [0, 3]}
    
    myDict[0].remove(myDict[0][0])
    myDict[0].remove(myDict[0][1])
    
    print(myDict)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2021-07-11
      相关资源
      最近更新 更多