我需要过滤一个二维数组,让我们说
[
[1, 'eth0', 'description', ...],
[2, 'virbr0', 'description', ...],
[3, 'qvb25f982e4-ae', 'description', ...],
[4, 'tap25f982e4-ae', 'description', ...],
...
]
基本上我想过滤掉某些界面名称。我过滤掉以q
开头的接口,如下所示:
info = [i for i in info if not i[1].startswith('q')]
但我需要能够定义要忽略的接口前缀列表,例如:
exclude = ['q','tap']
info = [i for i in info if not i[1].startswith(exclude)]
但我似乎无法找到类似这样的逻辑。
答案 0 :(得分:8)
你太近了!将exclude
变为元组:
exclude = ('q','tap')
info = [i for i in info if not i[1].startswith(exclude)]
... 前缀也可以是元组 1 的前缀来寻找....
演示:
>>> info = [
... [1, 'eth0', 'description'],
... [2, 'virbr0', 'description'],
... [3, 'qvb25f982e4-ae', 'description'],
... [4, 'tap25f982e4-ae', 'description'],
... ]
>>>
>>> exclude = ('q','tap')
>>> info = [i for i in info if not i[1].startswith(exclude)]
>>>
>>> info
[[1, 'eth0', 'description'], [2, 'virbr0', 'description']]
1 我加上了重点...