【问题标题】:Iterating through and removing from a value list of a dictionary遍历字典的值列表并从中删除
【发布时间】:2020-11-17 01:54:18
【问题描述】:

所以我抽象了一个我正在研究的项目,以测试如何在以列表为值的字典中添加和删除键和值。基本上我有一个字典,它的键/值对是频道名称和频道中的用户列表。

我最终弄清楚了如何附加值特定键创建具有预期值的新键,但从具有值列表的字典中删除预期值似乎更加困难。

我将快速描述有关此设计的一些简要细节,这些细节再次从项目中简化,用于测试目的,我猜只是时间。提示用户输入要从频道或频道列表中添加或删除的名称。格式是 JOIN/PART,后跟逗号分隔的“通道”列表。它看起来像加入#foo,#bar,#dog。对于测试符号实际上不是必需的,您也可以一次加入或离开 1 个频道。

我的问题出在 part() 函数中,我实际上无法找到一种方法来遍历频道以检测用户是否在频道中,然后将其从该频道中删除。

还有一个列表功能也用于测试目的,但非常简单地只是打印字典。

由于原始使用正则表达式来确保命令正确,我也没有对此进行错误检查,因此如果您脱离上述格式,它会破坏事情。

channels = {'#foo':['sean', 'john', 'tim'],
            '#bar':['sean', 'paul', 'tim'],
            '#cat':['paul', 'john', 'tim'],
            '#dog':['sam', 'john', 'tim']}

def part(name, channelNameList):
    for channelName in channelNameList:
        if channelName in channels:
            # if user is in the list remove them, else print user is not in list
            pass
        else:
            print("Channel {} does not exist")

def list():
    print(channels)

while True:
    name = input("Enter name: ")
    command = input("Enter command: ")
    
    if command == "list":
        list()
    else:
        removeCommand = command.split(" ", -1)
        params = removeCommand[1].split(",", -1)
        
        if removeCommand[0] == "PART":
            part(name, params)

【问题讨论】:

  • channelNameList 在您的 part() 函数中初始化为什么?
  • 哦,对不起,这是旧尝试的产物,为了清楚起见,我马上改变它@RedCricket
  • 您不需要使用any() 来检查项目是否在列表中。使用if user in channels[channelName]:

标签: python dictionary iteration


【解决方案1】:

使用remove() 从列表中删除一个元素。

def part(name, channelNameList):
    for channelName in channelNameList:
        if channelName in channels:
            try:
                channels[channelName].remove(name)
            except ValueError:
                print("User {} is not in {}".format(user, channelName)
        else:
            print("Channel {} does not exist")

【讨论】:

  • 谢谢@Barmar,我只是意识到在有人发布了关于删除的帖子后,我把这件事严重地复杂化了。我认为删除会做一些完全不同的事情,所以我早些时候取消了它作为一个选项的资格。
  • 我想你把它和del channels[channelName]混淆了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2019-11-29
相关资源
最近更新 更多