Python:想要返回与模式列表匹配的2D列表

时间:2016-01-30 23:02:57

标签: python regex list pattern-matching

我有一个名为input_list的元素的2D列表,如下所示。它包含各种嵌套列表,其中包含多个具有文本数据的列表元素。

input_list = [['UserName', 'EmailID', 'NoofLogins', 'Logs'],
              ['abariettq7g3sab9s2', 'abariett@polarstar.com', 1.0, 'User : Abariett has logged in successfully. $$'],
              ['adminadswdasdpj362xQ', 'admin@windacademy.us', 1.0, 'User : Admin has logged in successfully. $$ Scan Started Successfully for - Account Name : windacademy.us. $$'],
              ['adminadswdsaasdpjasxQ', 'archer@windacademy.us', 1.0, 'User : Admin has logged in successfully. $$ User kevin@gou.lo deleted $$'],
              ['abariettq7g3sab9s2', 'abariett@polarstar.com', 1.0, 'User : Abariett has logged out successfully. $$']
             ]

以下valid_pattern列表与input_list匹配,

valid_pattern = ['started', 'initiated', 'stopped', 'added', 'fetched', 'completed', 'deleted', 'updated', 'disabled']

来自二维input_list,我只想要与valid_pattern列表中的任何项目匹配的列表,如下所示。

output_list = [['adminadswdasdpj362xQ', 'admin@windacademy.us', 1.0, 'User : Admin has logged in successfully. $$ Scan Started Successfully for - Account Name : windacademy.us. $$']
               ['adminadswdsaasdpjasxQ', 'archer@windacademy.us', 1.0, 'User : Admin has logged in successfully. $$ User kevin@gou.lo deleted $$']
              ]

output_list中查看,在第一种情况下,唯一一个与模式元素开始匹配的嵌套列表,在第二种情况下,已删除。 如何获得此输出?

1 个答案:

答案 0 :(得分:0)

我建议也使用嵌套列表理解:

[i for i in input_list if any(j in str(i).lower() for j in valid_pattern)]

演示:

>>> pprint.pprint([i for i in input_list if any(j in str(i).lower() for j in valid_pattern)])
[['adminadswdasdpj362xQ',
  'admin@windacademy.us',
  1.0,
  'User : Admin has logged in successfully. $$ Scan Started Successfully for - '
  'Account Name : windacademy.us. $$'],
 ['adminadswdsaasdpjasxQ',
  'archer@windacademy.us',
  1.0,
  'User : Admin has logged in successfully. $$ User kevin@gou.lo deleted $$']]