有点复杂的列表理解

时间:2014-11-06 21:59:00

标签: python list-comprehension

我需要过滤一个二维数组,让我们说

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

但我似乎无法找到类似这样的逻辑。

1 个答案:

答案 0 :(得分:8)

你太近了!将exclude变为元组

exclude = ('q','tap')
info = [i for i in info if not i[1].startswith(exclude)]

来自documentation

  

... 前缀也可以是元组 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 我加上了重点...