Вопрос

I have files with words and i want to add them together and with the condition of unique words only. How to implement that? Here is the example :

words1 = {'view', 'lower', 'sample','good'}
words2 = {'sold', 'good', 'part', 'view'}

The answer should be :

words = {'view', 'lower', 'sample', 'good', 'sold', 'part'}
Это было полезно?

Решение

You have sets, and you want the union:

words = words1 | words2

where the Python set type has overloaded the | operator to return the union of two sets.

You can also use the explicit set.union() method:

words = words1.union(words2)

Demo:

>>> words1 = {'view', 'lower', 'sample','good'}
>>> words2 = {'sold', 'good', 'part', 'view'}
>>> words1 | words2
{'lower', 'good', 'sold', 'part', 'sample', 'view'}
>>> words1.union(words2)
{'lower', 'good', 'sold', 'part', 'sample', 'view'}

'view' and 'good' are present in both input sets, so the output is a set of 6 unique words.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top