[英]remove from a list of tuples according to the second part of the tuple in python
contacts.remove((name,ip))
我有ip,它是独一无二的。 我想根据ip从联系人中删除这个元组,而不需要命名。
我刚试过这个contacts.remove((pass,ip))
,但是我遇到了一个错误。
contacts = [(name, ip) for name, ip in contacts if ip != removable_ip]
要么
for x in xrange(len(contacts) - 1, -1, -1):
if contacts[x][1] == removable_ip:
del contacts[x]
break # removable_ip is allegedly unique
第一种方法将contacts
重新绑定到新创建的列表,该列表排除了所需的条目。 第二种方法更新原始列表; 它向后移动,以避免被del
声明绊倒在他脚下的地毯上。
由于要删除的ip
是唯一的,因此您不需要修改正在迭代的容器的所有常规预防措施 - 因此,最简单的方法是:
for i, (name, anip) in enumerate(contacts):
if anip == ip:
del contacts[i]
break
这回答了我未创造的问题。 感谢您的解释,但让我总结并概括多重删除和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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.