Hi,

I have jest started learning Python.

I would like to get some help on writing a script that would delete a data of lines only key from array which looks like this :

['192.168.255.1 00:01:02','172.14.0.1 00:0f:01','172.14.0.1 01:ff:dd:34' ,192.168.255.3 00:dd:01:ff


I want delet red data only

Recommended Answers

All 6 Replies

You simply form a new list excluding the item that contain a given substring ...

mylist = [
'192.168.255.1 00:01:02',
'172.14.0.1 00:0f:01',
'172.14.0.1 01:ff:dd:34',
'192.168.255.3 00:dd:01:ff'
]

exclude = '172.14.0.1'
newlist = []
for item in mylist:
    if exclude not in item:
        newlist.append(item)

print(newlist)

"""my result -->
['192.168.255.1 00:01:02', '192.168.255.3 00:dd:01:ff']
"""

if i want to delete red data of only key '172.14' all in from array

mylist = [
'192.168.255.1 00:01:02',
'172.14.0.1 00:0f:01',
'172.14.0.2 00:0f:01',
'172.14.0.3 00:0f:01'
'172.14.0.4 01:ff:dd:34',
'192.168.255.3 00:dd:01:ff'
]

if i want to delete red data of only key '172.14' all in from array

You can use vega code for this.

mylist = newlist
print(mylist)

So now mylist has removed item you want(garbage collection)old mylist do not exits.

Or an another soultion.

mylist = [
'192.168.255.1 00:01:02',
'172.14.0.1 00:0f:01',
'172.14.0.2 00:0f:01',
'172.14.0.3 00:0f:01'
'172.14.0.4 01:ff:dd:34',
'192.168.255.3 00:dd:01:ff'
]

for item in mylist[:]:
    if item.startswith('172'):        
        mylist.remove(item)   
        
print mylist

The example code will simply change to this ...

mylist = [
'192.168.255.1 00:01:02',
'172.14.0.1 00:0f:01',
'172.14.0.2 00:0f:01',
'172.14.0.3 00:0f:01'
'172.14.0.4 01:ff:dd:34',
'192.168.255.3 00:dd:01:ff'
]

exclude = '172.14'  # adjusted to new exclude criteria
newlist = []
for item in mylist:
    if exclude not in item:
        newlist.append(item)

print(newlist)

"""my result -->
['192.168.255.1 00:01:02', '192.168.255.3 00:dd:01:ff']
"""

Really Pythonic (elegant) ...

mylist = [
'192.168.255.1 00:01:02',
'172.14.0.1 00:0f:01',
'172.14.0.2 00:0f:01',
'172.14.0.3 00:0f:01'
'172.14.0.4 01:ff:dd:34',
'192.168.255.3 00:dd:01:ff'
]

# your exclude substring
exclude = '172.14'
newlist = [item for item in mylist if not item.startswith(exclude)]
print(newlist)

"""output -->
['192.168.255.1 00:01:02', '192.168.255.3 00:dd:01:ff']
"""

thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.