Remove from tuple list according to second part of tuple in python

contacts.remove((name,ip))

I have ip and it is unique. I want to remove this tuple from contacts according to ip and no need to specify.

I just tried this contacts.remove((pass,ip)), but I ran into an error.

+3
source share
3 answers
contacts = [(name, ip) for name, ip in contacts if ip != removable_ip]

or

for x in xrange(len(contacts) - 1, -1, -1):
    if contacts[x][1] == removable_ip:
        del contacts[x]
        break # removable_ip is allegedly unique

The first method reorders contactsto a newly created list that excludes the desired entry. The second method updates the original list; he goes back so as not to be stressed by the operator delmoving the mat under his feet.

+11
source

ip , , , - , :

for i, (name, anip) in enumerate(contacts):
  if anip == ip:
    del contacts[i]
    break
+4

This answers my not created question. Thanks for the explanation, but let me generalize and generalize the answers for multiple deletion and Python 3.

list = [('ADC', 3),
        ('UART', 1),
        ('RemoveMePlease', 42),
        ('PWM', 2),
        ('MeTooPlease', 6)]

list1 = [(d, q)
         for d, q in list
         if d not in {'RemoveMePlease', 'MeTooPlease'}]

print(list1)

for i, (d, q) in enumerate(list):
    if d in {'RemoveMePlease', 'MeTooPlease'}:
        del(list[i])

print(list)

Relevant Help Topic

+1
source

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


All Articles