在Python中查找列表中的部分匹配

2 投票
3 回答
2430 浏览
提问于 2025-04-18 07:05

我有一个包含多个列表的列表,我需要找到并打印出那些包含完全匹配和部分匹配的列表,忽略大小写。

l = [['2014','127.0.0.1','127','DNS sever Misconfiguration'],['2014','192.168.1.25','529','Failed logon for user user1'],['2014','127.0.0.1','1','This is a test message']]

条件1和条件2可以是任何东西,比如说 '192.186.1.25' 或者 'failed'

>>> for i in l:
        if 'condition 1' in i and 'condition2' in i:
           print i

结果是... 什么都没有

我只能使用一个条件进行精确匹配,并且能得到结果

>>> for i in l:
      if '127.0.0.1' in i:
        print i


['2014', '127.0.0.1', '127', 'DNS sever Misconfiguration']
['2014', '127.0.0.1', '1', 'This is a test message']

任何帮助都会很感激

3 个回答

0

这是我尝试的结果:

l = [['2014','127.0.0.1','127','DNS sever Misconfiguration'],    ['2014','192.168.1.25','529','Failed logon for user user1'],['2014','127.0.0.1','1','This is a test message']]

condition1 = 'Failed'
condition2 = '2014'

for lst in l:
    found_cond1 = False
    found_cond2 = False
    for string in lst:
        if condition1 in string:
            found_cond1 = True
        if condition2 in string:
            found_cond2 = True
        if found_cond1 and found_cond2:
            print(lst)
            break

得到的结果是

['2014', '192.168.1.25', '529', 'Failed logon for user user1']
1
'condition 1' in i

这段代码会搜索字符串字面量 'condition 1'。不过,我觉得你想要搜索的是由 名称 condition1 指向的对象,也就是:

condition1 in l

如果你想要“部分”匹配,可以使用 or

if condition1 in l or condition2 in l:

或者使用 any()

if any(cond in l for cond in (condition1, condition2)):
2

我猜你的第二个条件没有匹配好,比如你如果这样做:

'127.0.0.1' in i and 'Misconfiguration' in i

但是 i 看起来像:

['2014', '127.0.0.1', '127', 'DNS sever Misconfiguration']

那么 '127.0.0.1' 会在 i 里面,但 'Misconfiguration' 就不会了——因为这是一个列表,而在列表中使用 in 是要求完全匹配的,但你想要的是 i 中某个元素的子字符串。如果这些条件是一致的,你可以这样做:

'127.0.0.1' in i and 'Misconfiguration' in i[3]

或者如果它们不一致,你需要检查所有条目的子字符串:

'127.0.0.1' in i and any('Misconfiguration' in x for x in i)

这样就可以了。这个方法会检查 i 中每个项目是否包含你的搜索词。

撰写回答