在putty terminal中以彩色打印集合中的项目时,获取错误“不支持的操作数类型(用于“^:'str'和'set')”

2024-04-30 03:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两套:set1和set2。我能够在终端中以绿色打印set1项目,以便在打印输出差异时,很容易识别哪个项目来自哪个集合,但在以绿色打印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']

Tags: the项目in差异listprintsetjacob
1条回答
网友
1楼 · 发布于 2024-04-30 03:07:40

问题是,当您对集合进行如下着色时:

from termcolor import colored
set1 = {'Amy', 'Jacob'}
set2 = {'Jacob', 'Serp'}
set12 = colored(set1, 'green')
print(set12)
print(type(set12))

输出:
enter image description here

正如您所看到的,该集合被铸造为一个彩色的字符串,并且您使用字符串来区分集合,所以这就是错误的原因。 另一种方法是更改集合中的每个元素,但这不起作用,因为当您为字符串着色时,会添加一些字符以提供该颜色,如下图所示,因此当您执行此操作时,它将输出两个串联的集合:

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)

输出:
enter image description here

您可以尝试的方法是获取差异,如果差异的某个元素在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 }),']')

输出:
enter image description here

相关问题 更多 >