Find out if an element is present in a multidimensional array in python

I am parsing a log containing aliases and host names. I want to get an array containing the host name and last used alias.

I have the following code that only creates a list by hostnames:

hostnames = [] # while(parsing): # nick = nick_on_current_line # host = host_on_current_line if host in hostnames: # Hostname is already present. pass else: # Hostname is not present hostnames.append(host) print hostnames # [' foo@google.com ', ' bar@hotmail.com ', ' hi@to.you '] 

I thought it would be nice to end up with something like the following:

 # [[' foo@google.com ', 'John'], [' bar@hotmail.com ', 'Mary'], [' hi@to.you ', 'Joe']] 

My problem is that the hostname is on such a list

 hostnames = [] # while(parsing): # nick = nick_on_current_line # host = host_on_current_line if host in hostnames[0]: # This doesn't work. # Hostname is already present. # Somehow check if the nick stored together # with the hostname is the latest one else: # Hostname is not present hostnames.append([host, nick]) 

Is there any easy solution for this, or should I try a different approach? I always had an array with objects or structures (if python has such a thing), but I would prefer a solution to the problem with my array.

+4
source share
3 answers

Just use the dictionary.

 names = {} while(parsing): nick = nick_on_current_line host = host_on_current_line names[host] = nick 
+3
source

Use a dictionary instead of a list. Use the host name as the key and the username as the value.

+4
source
 if host in zip(*hostnames)[0]: 

or

 if host in (x[0] for x in hostnames): 
+2
source

Source: https://habr.com/ru/post/1308559/


All Articles