我有一个看起来像这样的元组
full = [('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected'),('Port-Channel545', 'odsa', 'connected')]
我想删除所有端口 channel 以仅返回接口(interface)。我可以对列表中的每个 Port-Channel 进行硬编码并以这种方式将其删除,但这不是很可扩展。我试图从列表中删除任何带有“端口”的内容,所以我的脚本看起来像这样
full = [('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected')]
skip_interfaces = ['Ethernet49/1', 'Ethernet49/2', 'Ethernet49/3', 'Ethernet49/4', 'Ethernet50/1', 'Ethernet50/2', 'Ethernet50/3','Ethernet50/4','Ethernet51/1',
'Ethernet51/2', 'Ethernet51/3', 'Ethernet51/4', 'Ethernet52/1', 'Ethernet52/2', 'Ethernet52/3', 'Ethernet52/4', 'Port', 'Management1', 'Port-Channel44', 'Port-Channel34']
new = [tup for tup in full if tup[0] not in skip_interfaces]
print new
但是当打印出来的时候我还是得到了
[('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected'),('Port-Channel545', 'odsa', 'connected')]
当列表中有子字符串时,是否有更好的方法从元组中删除项目?
谢谢
最佳答案
您可以使用 str.startswith
使用列表推导过滤掉第一个元素以“Port”或“Port-Channel”开头的所有元组。 str.startwsith
可以与下面列出的几个替代方案结合使用。
选项 1
列表理解
>>> [i for i in full if not i[0].startswith('Port')] # .startswith('Port-Channel')
[('Ethernet4/3', 'odsa', 'connected')]
或者,您可以对i[0]
执行not in
检查,这将根据i[0]
是否过滤元素在任何地方都包含“端口”。
>>> [i for i in full if 'Port' not in i[0]]
[('Ethernet4/3', 'odsa', 'connected')]
选项 2
普通 for
循环
第二种方法(与第一种方法非常相似)是使用普通的 for
循环。遍历 full
并使用 if
子句进行检查。
r = []
for i in full:
if not i[0].startswith('Port'):
r.append(i)
选项 3
过滤器
filter
是这里的另一种选择。 filter
删除不符合特定条件的元素。这里的条件是第一个参数,作为 lambda
传递。第二个参数是要过滤的列表。
>>> list(filter(lambda x: not x[0].startswith('Port'), full))
[('Ethernet4/3', 'odsa', 'connected')]
与列表理解相比,filter
通常较慢。对于简洁的代码和在更大的管道中链接更多表达式仍然是一个有用的结构。
注意:您应该永远不要使用删除和remove
和删除
。这会导致您的列表缩小,最终结果是循环将没有机会完全遍历列表元素。
关于python - 如果存在子字符串,则从元组中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48076228/