如何突出显示 python 匹配的列表元素?

How to highlight the python matching list elements?

我已经成功地比较了两个列表并且可以获得匹配的元素,但是我需要的输出应该显示第一个列表,其元素突出显示匹配的元素。示例:

list1 = [a,b,c,d,e,f,g]
list2 = [e,f,g,h,i,j,k]

output = [a,b,c,d,/e/,/f/,/g/]
list1 = list('abcdefg')
list2 = list('efghijk')
result = ['/{}/'.format(l) if l in list2 else l for l in list1]
print(result)

您不能突出显示元素,但您可以大写:

list1 = ['a','b','c','d','e','f']
list2 = ['e','f','i','j','k','a']

common = [i.upper() for i in list1 if i in list2]
notCommon = [i for i in list(set(list1+list2)) if i.upper() not in common]

output = common+notCommon

print output

Returns:

['A', 'E', 'F', 'c', 'b', 'd', 'i', 'k', 'j']

不确定这是否有效,但根据您的输出,我们可以这样做。我还假设列表中有字符串。

>>> list1
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> list2
['e', 'f', 'g', 'h', 'i', 'j', 'k']
>>> list3 = list(set(list1).intersection(list2))
>>> list3
['e', 'g', 'f']
>>> for i in list3:
...     list1[list1.index(i)] = '/'+i+'/'
... 
>>> list1
['a', 'b', 'c', 'd', '/e/', '/f/', '/g/']
>>>