首页 > 解决方案 > 如何从列表的所有元素中替换冒号 (:)?

问题描述

嗨,让我解释一下我想要做什么。我正在做一个有趣的项目,只是为了体验。我打算用python制作一个程序,我想在其中提供所有连接到我的家庭wifi网络的mac地址,如果我提供的mac地址已经在列表中(我已经保存了),程序会给我一个输出) 或者它是一个新的 mac 地址。

我制作了所有已知mac地址的字典

reg_mac = {
    "Device A" : "00:00:00:00:00:00",
    "Device B" : "00:00:00:00:00:00",
    "Device C" : "00:00:00:00:00:00",
    "Device D" : "00:00:00:00:00:00",
    "Device E" : "00:00:00:00:00:00"
}

然后我替换了字典(值)中的所有冒号,并将其替换为""没有空格。

res = {key:value.replace(':', '') for key,value in reg_mac.items()}

我得到了这个

reg_mac = {
    "Device A" : "000000000000",
    "Device B" : "000000000000",
    "Device C" : "000000000000",
    "Device D" : "000000000000",
    "Device E" : "000000000000"
}

然后我要求用户输入mac地址列表

num = int(input('Size of elements : '))
arr = list()

for i in range(num) :
  ele  = (input())
  arr.append(ele)

**现在我想将列表元素 [00:00:00:00:00] 中的所有冒号“:”替换为 [0000000000]

然后我想打印

如果 mac 地址在我们的字典中可用
print "This is {key}"
else
print "This is a new device"

我是 python 新手,一般来说是计算机编程新手。这是我的第一个有趣的小项目。如果有人在这方面帮助我,我完成了我的第一个项目,这将提高我的兴趣,我将开始从事新项目。

顺便说一句,我是新手,仍在网上学习我的 Python 课程

标签: pythonlistconditional-operatormac-address

解决方案


如果要检查字典中是否有值,则需要使用.values()方法。

if mac in reg_mac.values():
    print("This is {key}")

else:
    print("This is a new device")

推荐阅读