Получение ошибки «неподдерживаемые типы операндов для ^: 'str' и 'set'» при печати элементов набора в цвете в терминале шпатлевки - PullRequest
1 голос
/ 21 июня 2020

У меня 2 комплекта: 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', 'Serp']

1 Ответ

3 голосов
/ 21 июня 2020

Проблема в том, что когда вы раскрашиваете набор так:

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

Вывод: enter image description here

The set is casted to a string colored as you could see, and you were diferencing a set with a string, so that's why the error. Another way to do it could be change every element of the set, but this doesn't work, because when you colored a string, you are appending some characters to give that color, as you can see below, so when you do the differnce it will output te two sets concatenated:

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)

Output:
enter image description here

The way that you can try is to get the difference, and if some element of the difference is in set1, color it with green, and then join them into a string to color the print:

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 }),']')

Output:
введите описание изображения здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...