嵌套列表 -Python

Nested List -Python

我有两个列表。我想将每个列表的 "a" 的列表索引 [1][2][3] 与 "b" 的其他列表索引[1][2][3] 进行比较。如果如果匹配则忽略,如果不匹配则 return 整个列表。

a = [['Eth1/1/13', 'Marketing', 'connected', '10', 'full', 'a-1000'], ['Eth1/1/14', 'NETFLOW02', 'connected', '10', 'full', '100']]

b = [['Eth1/1/13', 'NETFLOW02', 'connected', '15', 'full', '100'], ['Eth1/1/14', 'Marketing', 'connected', '10', 'full', 'a-1000']]

期望的输出:

Diff a:

Eth1/1/14  NETFLOW02   connected    10   full    100

Diff b:

Eth1/1/13  NETFLOW02    connected    15   full    100

我正在尝试什么:

p = [i for i in a if i not in b]
for item in p: 
      print item[0]
print "\n++++++++++++++++++++++++++++++\n"
q = [i for i in b if i not in a]
for item in q: 
      print item[0]

在下面尝试过,但只能匹配内部列表的索引 1,索引 2 和 3 仍然需要匹配..

[o for o in a if o[1] not in [n[1] for n in b]

我没有得到预期的 output.Any 如何做到这一点的想法?

for sublista in a:
    if not any(sublista[1:4] == sublistb[1:4] for sublistb in b):
        print(sublista)

您需要一个内部循环,以便可以将列表 a 中的每个 子列表 与每个 子列表[=51= 进行比较] 在列表 b 中。内部循环通过 generator expression. Slices are used to to compare only a portion of the sub-lists. The built-in function any consumes the generator expression; it is lazy 完成,并将 return Truefirst True 等价比较。这将打印 a 中每个 sub-listb 中没有匹配的每个 sub-list - 打印每个 sub-list in ba 中没有匹配项,将 b 放入外循环,将 a 放入内循环。

这是不使用生成器表达式或 any:

的等价物
for sublista in a:
    equal = False
    for sublistb in b:
        if sublista[1:4] == sublistb[1:4]:
            break
    else:
        print(sublista)

有时使用 operator.itemgetter 很好,因此您可以为切片使用名称,这可以使代码更易于理解。:

import operator
good_stuff = operator.itemgetter(1,2,3)
for sublista in a:
    if not any(good_stuff(sublista) == good_stuff(sublistb) for sublistb in b):
        print(sublista)

itertools.product conveniently generates pairs and can be used as a substitute for the nested loops above. The following uses a dictionary (defaultdict) 保存 ab 中每个子列表的比较结果,然后检查是否存在匹配项 - 它同时执行 abba 比较。

import itertools, collections
pairs = itertools.product(a, b)
results = collections.defaultdict(list)
for sub_one, sub_two in pairs:
    comparison = good_stuff(sub_one) == good_stuff(sub_two)
    results[tuple(sub_one)].append(comparison)
    results[tuple(sub_two)].append(comparison)

for sublist, comparisons in results.items():
    if any(comparisons):
        continue
    print(sublist)

# or
from pprint import pprint
results = [sublist for sublist, comparisons in results.items() if not any(comparisons)]
pprint(results)
for v in a,b:
    for items in v:
        if 'NETFLOW02' in items:
            print('\t'.join(items))

我不确定这是否适合您的目的,但您似乎想从这两个列表中捕获名为 NETFLOW02 的网络接口的结果。

我确定这可能是不可接受的原因,但您也可以将其扩展为在更长的列表中包含其他关键字,好吧,根据您的问题中的解释,任何长度的嵌套列表。为此,您需要创建另一个列表,假设为 keywords = ['NETFLOW02','ETH01']

然后我们也简单地迭代这个列表。

results = []
for v in a,b:
    for item in v:
        for kw in keywords:
            if kw in item:
            results.append(item)
            print('\t'.join(item))
print(results)