I have a list of lists as follows:
aList= [['192.168.1.3', '0080.4522.ad08', '2013/05/02 19:10:10', 'automatic'],
['192.168.1.2', '0080.4522.ad08', '2013/05/02 19:05:00', 'automatic']]
When adding another list I want to check if the ip or mac address are in another list before adding them, if they are already in the list of lists I don't want to add them. For instance if I was testing 192.168.1.3 it would not add it to the list as that element exists somewhere already. So I may be trying to add this list again but I want it to fail:
['192.168.1.3', '0080.4522.ad08', '2013/05/02 19:10:10', 'automatic']
The way I have been doing it is looping through the lists and setting a boolean once the element is found, but I don't feel this way is great. How would you do it? I know that IP will always be element one of each list but relying on index also seems a bad way to do things.
You can use any
:
>>> lis = ['192.168.1.3', '0080.4522.ad08', '2013/05/02 19:10:10', 'automatic']
if any(item[0] == lis[0] or item[1] == lis[1] for item in aList)
#then don't add
else:
#add
A good way to solve this is to use objects, and make the list a list of objects instead of a list of list/tuples. You could then override the compare-function for objects and use the normal "in" statement.
class Client:
def __init__(self, ip, mac, timedate, mode):
self.ip = ip
self.mac = mac
self.timedate = timedate
self.mode = mode
def __eq__(self, object):
if type(object) != type(self):
return False
if object.ip == self.ip or object.mac == self.mac
return True
return False
you could then do something like
client = Client("127.0.0.1", "abwdds", date, mode)
if client not in list:
doSomething()
list.append(client)
如果IP地址是数据的关键列,则应使用字典将IP地址与其他列映射到元组(或列表)。
Use a dictionary to hold your connections.
cons = [{'IP':'192.168.1.3', 'MAC':'0080.4522.ad08', 'timestamp':'2013/05/02 19:10:10', 'type':'automatic'},
{'IP':'192.168.1.2', 'MAC':'0080.4522.ad08', 'timestamp':'2013/05/02 19:05:00', 'type':'automatic'}]
def add_con(con):
if any((con['IP'] == c['IP'] or con['MAC'] == c['MAC']) for c in con):
# duplicate
else:
# new
You could easily wrap this functionality into a class.
class ConnectionManager():
def __init__(self):
self.connections = []
def add_con(ip, mac, timestamp, mode):
if any((ip == c['IP'] or mac == c['MAC']) for c in self.connections):
# duplicate
return False # possible option?
else:
self.connections.append({'IP':ip, 'MAC':mac, 'timestamp':timestamp, 'mode':mode})
return True # possible option?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.