简体   繁体   中英

remove from a list of tuples according to the second part of the tuple in python

contacts.remove((name,ip))

I have the ip and it's unique. I want to remove this tuple from contacts according to the ip and no need to name.

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

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 rebinds contacts to a newly-created list that excludes the desired entry. The second method updates the original list; it goes backwards to avoid being tripped up by the del statement moving the rug under its feet.

Since the ip to remove is unique, you don't need all the usual precautions about modifying a container you're iterating on -- thus, the simplest approach becomes:

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

This answers my not created question. Thanks for the explanation, but let me summarize 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)

The corresponding help topic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM