contacts.remove((name,ip))
contacts.remove((名称,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.
我有ip,它是独一无二的。我想根据ip从联系人中删除这个元组,不需要命名。
I just tried this contacts.remove((pass,ip))
, but I encountered an error.
我刚试过这个contacts.remove((pass,ip)),但是我遇到了一个错误。
3 个解决方案
#1
11
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.
第一种方法将联系人重新绑定到新创建的列表,该列表排除了所需的条目。第二种方法更新原始列表;它向后移动以避免被del声明移动地毯下的地毯绊倒。
#2
4
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:
由于要删除的ip是唯一的,因此您不需要修改正在迭代的容器的所有常规预防措施 - 因此,最简单的方法是:
for i, (name, anip) in enumerate(contacts):
if anip == ip:
del contacts[i]
break
#3
1
This answers my not created question. Thanks for the explanation, but let me summarize and generalize the answers for multiple deletion and Python 3.
这回答了我未创造的问题。感谢您的解释,但让我总结并概括多重删除和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)
相应的帮助主题
#1
11
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.
第一种方法将联系人重新绑定到新创建的列表,该列表排除了所需的条目。第二种方法更新原始列表;它向后移动以避免被del声明移动地毯下的地毯绊倒。
#2
4
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:
由于要删除的ip是唯一的,因此您不需要修改正在迭代的容器的所有常规预防措施 - 因此,最简单的方法是:
for i, (name, anip) in enumerate(contacts):
if anip == ip:
del contacts[i]
break
#3
1
This answers my not created question. Thanks for the explanation, but let me summarize and generalize the answers for multiple deletion and Python 3.
这回答了我未创造的问题。感谢您的解释,但让我总结并概括多重删除和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)
相应的帮助主题