contacts.remove(开发者_C百科(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
精彩评论