嗨,让我解释一下我想做什么。我正在做一个有趣的项目,只是为了积累经验.我打算在python中做一个程序,我想给所有的mac地址,连接到我家的wifi网络和程序给我一个输出,如果我给的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"
}
然后,我把字典中的冒号(value)全部替换为 ""
没有空间。
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]中的所有冒号": "替换为[00000000]。
然后我想打印
如果我们的字典里有mac地址,则打印 "这是{key}",否则打印 "这是一个新设备"
我是python的新手,也是一般的计算机编程新手。这是我的第一个有趣的小项目。如果有人帮助我,我完成了我的第一个项目,这将提高我的兴趣,我将开始工作的新项目。
顺便说一下 我是一个新手,还在网上学习我的python课程。
如果你想检查是否有一个值在字典中,你需要使用 .values()
方法。
if mac in reg_mac.values():
print("This is {key}")
else:
print("This is a new device")
这是你要找的吗?
def address_already_exists(key):
result = []
for i in range(6):
result.append(key[2*i:2*(i+1)])
return ":".join(result)
print(address_already_exists("000000000000")) # prints 00:00:00:00:00:00
列表理解中的mac过滤器,每2个分开,连接在": "上。
matches = filter(lambda x: x[1] in arr,reg_mac.items())
# create res dict key:value of matching macs with colons
res = {k:":".join(v[i:i+2] for i in range(0,len(v),2)) for k,v in matches}
[print(k,v) for k,v in res.items()] #print k and v for each
你可以使用 dict.items()
来找到该值所属的键。
mac = input("Input mac adress: ")
for m, a in reg_mac.items():
if mac == a:
print(f"This is {m}")
else:
print("This is a new device")
你也可以只用 dict.keys()
:
mac = input("Input mac adress: ")
for m in reg_mac.keys():
if mac == reg_mac[m]:
print(f"This is {m}")
else:
print("This is a new device")
So finally i found my answer and now my program is working perfectly fine.I am sharing my working code down below:
reg_mac = {
"Device A" : "00:00:00:00:00:01",
"Device B" : "00:00:00:00:00:02",
"Device C" : "00:00:00:00:00:03",
"Device D" : "00:00:00:00:00:04",
"Device E" : "00:00:00:00:00:05",
"Device F" : "00:00:00:00:00:06",
"Device G" : "00:00:00:00:00:07",
"Device H" : "00:00:00:00:00:08",
"Device I" : "00:00:00:00:00:09",
"Device J" : "00:00:00:00:00:10"
}
reg_mac = {key:value.replace(':', '') for key,value in reg_mac.items()}
num = int(input('Size of elements : '))
arr = list()
for i in range(num) :
ele = (input())
arr.append(ele)
new_lst = [i.replace(":","") for i in arr]
print(new_lst)
for val in new_lst:
if val in list(reg_mac.values()):
print(f"the device is {list(reg_mac.keys())[list(reg_mac.values()).index(val)]}")
else:
print("Unknown Device")