如果子字符串存在,则从元组中删除项目

问题描述 投票:3回答:1

我有一个看起来像这样的元组

full = [('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected'),('Port-Channel545', 'odsa', 'connected')]

我想删除所有Port-Channels以仅返回接口。我可以在列表中硬编码每个Port-Channel并以这种方式删除它,但这不是很可扩展。我正试图从列表中删除任何带有“Port”的内容,所以我的脚本看起来像这样

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')]

当子字符串在列表中时,是否有更好的方法从元组中删除项目?

谢谢

python list tuples
1个回答
6
投票

您可以使用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')]

或者,您可以对not in执行i[0]检查,i[0]将根据>>> [i for i in full if 'Port' not in i[0]] [('Ethernet4/3', 'odsa', 'connected')] 是否在任何地方包含“Port”来过滤元素。

for

选项2 香草for循环 第二种方法(与第一种方法非常相似)是使用普通的'full循环。迭代if并使用r = [] for i in full: if not i[0].startswith('Port'): r.append(i) 条款进行检查。

filter

选项3 filter filter是另一种选择。 lambda删除不符合特定条件的元素。这里的条件是第一个参数,作为>>> list(filter(lambda x: not x[0].startswith('Port'), full)) [('Ethernet4/3', 'odsa', 'connected')] 传递。第二个参数是要过滤的列表。

filter

与列表理解相比,remove通常较慢。仍然是一个有用的构造,用于简洁的代码,并在更大的管道中链接更多的表达式。


注意:您不应该使用循环遍历列表并使用del和qazxswpoi等方法删除元素。这会导致列表缩小,最终结果是循环没有机会完全遍历列表元素。

© www.soinside.com 2019 - 2024. All rights reserved.