Mohamed
Mohamed

Reputation: 51

How to replace IP Addresses as strings in a list to sort strings in python with checking out the repetitions between IP Addresses

If I have a list has the format below:

List1 = ['0.0.0.0', '192.168.1.193', '192.168.1.120', '10.0.0.155', '0.0.0.0',
         '192.168.1.240', '192.168.0.242','192.168.1.120']

I would like to know if there is any possibility to replace the IP Addresses in List1 to short strings with taking into consideration the repetitions between IP Addresses to get the List 2 below:

List1 = ['IP1','IP2','IP3','IP4','IP1','IP5','IP6'.'IP3']

The Repetitions of IP Addresses can be in anywhere (or location) in the List1.

Upvotes: 1

Views: 207

Answers (2)

Jarvis
Jarvis

Reputation: 8564

Toned down version:

dic = {}
for i in List1:
    if i not in dic:
        dic[i] = f"IP{len(dic)+1}"

After mapping elements in the original list to their name representations IP$N, you just map the values (strings) from keys(original IP addresses) of the dict to the original list:

List1 = list(map(lambda x: dic[x], List1))

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51683

Algo:

  • create an empty lookup dictionary
  • create a number-variable for your placeholders
  • iterate once through your list
    • if item not in dictionary
      • assign as key and as value assign it a placeholderstring
      • increment the placeholder number after adding
    • if item in dict already, ignore
  • create a new list by looking up each element of your original list in the dict and use the placeholder string instead

to get a list of those placeholders:

data = ['0.0.0.0', '192.168.1.193', '192.168.1.120', '10.0.0.155', '0.0.0.0',
        '192.168.1.240', '192.168.0.242','192.168.1.120']

# create lookup dict
ips = {} 
n= 1
for thing in data:
    if thing not in ips:
        ips[thing] = f"IP{n}"
        n += 1

# create looked up value list
rv = [ips[k] for k in data]

print(rv)

Output:

['IP1', 'IP2', 'IP3', 'IP4', 'IP1', 'IP5', 'IP6', 'IP3']

Upvotes: 1

Related Questions