我有2套:set1和set2。我能够在终端中以绿色打印set1的项目,以便在打印输出差异时轻松识别哪个项目来自哪个set,但是在以绿色打印set1项目的差异时会出错。我正在使用python 3.4.4
2套:
set1 = {'Amy', 'Jacob'}
set2 = {'Jacob', 'Serp'}
print(list(set1 ^ set2)) #printing the differences between two sets in below output. Using list because there will may sets and all the differences will be in list
['Amy', 'Serp']
我尝试使用termcolor,它能够以绿色打印set1的项目
from termcolor import colored
set1 =colored(set(x[key1]), 'green')
但是当使用以下代码打印差异时
set1 =colored(set(x[key1]), 'green')
set2 = {'Jacob', 'Serp'}
print(list(set1 ^ set2))
出现以下错误,因此我无法在输出中以绿色打印set1的项目,这是两组之间的差异
Traceback (most recent call last):
File "main.py", line 43, in <module>
print((set1 ^ set2))
TypeError: unsupported operand type(s) for ^: 'str' and 'set'
预期的输出低于应将Amy写入绿色的位置。
['Amy', 'Serp']
问题是,当您像这样对集合着色时:
from termcolor import colored
set1 = {'Amy', 'Jacob'}
set2 = {'Jacob', 'Serp'}
set12 = colored(set1, 'green')
print(set12)
print(type(set12))
如您所见,该集合被强制转换为带有颜色的字符串,并且您正在将一个集合与字符串区别开,因此这就是错误的原因。另一种方法是更改集合中的每个元素,但这是行不通的,因为在给字符串上色时,您将附加一些字符以赋予该颜色,如下所示,因此在进行区别时它将输出两个并置的集合:
from termcolor import colored
set1 = {'Amy', 'Jacob'}
set2 = {'Jacob', 'Serp'}
set11 = {colored(i, 'green') for i in set1}
print(set11)
print(type(set11))
print(set11^set2)
您可以尝试获得差异,如果差异中的某些元素在中set1
,请用绿色上色,然后将它们连接到字符串中以对印刷品上色:
from termcolor import colored
set1 = {'Amy', 'Jacob'}
set2 = {'Jacob', 'Serp'}
print('[', ', '.join({colored(i, 'green') if i in set1 else i for i in set1^set2 }),']')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句