CEa*_*onn 3 python tuples list
我有一个看起来像这样的元组
full = [('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected'),('Port-Channel545', 'odsa', 'connected')]
Run Code Online (Sandbox Code Playgroud)
我想删除所有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
Run Code Online (Sandbox Code Playgroud)
但是当打印出来时我仍然会得到
[('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected'),('Port-Channel545', 'odsa', 'connected')]
Run Code Online (Sandbox Code Playgroud)
当子字符串在列表中时,是否有更好的方法从元组中删除项目?
谢谢
您可以使用列表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')]
Run Code Online (Sandbox Code Playgroud)
或者,您可以执行not in检查i[0],这将根据是否i[0]在任何地方包含"端口" 来过滤元素.
>>> [i for i in full if 'Port' not in i[0]]
[('Ethernet4/3', 'odsa', 'connected')]
Run Code Online (Sandbox Code Playgroud)
选项2
vanilla for循环
第二种方法(非常类似于第一种方法)是使用普通的ol' for循环.迭代full并检查一个if条款.
r = []
for i in full:
if not i[0].startswith('Port'):
r.append(i)
Run Code Online (Sandbox Code Playgroud)
选项3是另一种选择.的除去不符合特定条件的元素.这里的条件是第一个参数,作为一个传递.第二个参数是要过滤的列表.
filter
filterfilterlambda
>>> list(filter(lambda x: not x[0].startswith('Port'), full))
[('Ethernet4/3', 'odsa', 'connected')]
Run Code Online (Sandbox Code Playgroud)
filter与列表理解相比,通常较慢.仍然是一个有用的构造,用于简洁的代码,并在更大的管道中链接更多的表达式.
注意:您应该永远不会遍历列表,并附有环和删除元素的地方,使用方法,如remove和del.这会导致列表缩小,最终结果是循环没有机会完全遍历列表元素.
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |