Reputation: 51
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
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
Reputation: 51683
Algo:
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