Sets in python
Содержание:
chain(*iterables)
Итератор chain берет ряд итерируемых, и лепит из них одну длинную итерируемую. Недавно это очень выручило меня во время работы над одним проектом. В общем, у нас есть список с определенными объектами, и два других списка, которые нам нужно добавить в общий список, но нам нужно только присоединить объекты каждого списка с объектами общего списка, а не создавать список списков. Изначально я попробовал сделать как-то так:
Python
my_list =
numbers = list(range(5))
cmd = [‘ls’, ‘/some/dir’]
my_list.extend(cmd, numbers)
print(my_list)
# [‘foo’, ‘bar’, [‘ls’, ‘/some/dir’], ]
1 |
my_list=’foo’,’bar’ numbers=list(range(5)) cmd=’ls’,’/some/dir’ my_list.extend(cmd,numbers) print(my_list) # [‘foo’, ‘bar’, [‘ls’, ‘/some/dir’], ] |
К сожалению, это не сработало так, как я ожидал. Модуль itertools предоставляет более элегантный способ совмещения этих списков в один при помощи chain:
Python
from itertools import chain
numbers = list(range(5))
cmd = [‘ls’, ‘/some/dir’]
my_list = list(chain(, cmd, numbers))
print(my_list)
# [‘foo’, ‘bar’, ‘ls’, ‘/some/dir’, 0, 1, 2, 3, 4]
1 |
fromitertoolsimportchain numbers=list(range(5)) cmd=’ls’,’/some/dir’ my_list=list(chain(‘foo’,’bar’,cmd,numbers)) print(my_list) # [‘foo’, ‘bar’, ‘ls’, ‘/some/dir’, 0, 1, 2, 3, 4] |
Самые проницательные мои читатели могут заметить, что здесь виден другой способ, которым можно достичь той же цели без использования itertools. Вы можете сделать следующее, для получения аналогичного результата:
Python
my_list =
my_list += cmd + numbers
print(my_list)
# [‘foo’, ‘bar’, ‘ls’, ‘/some/dir’, 0, 1, 2, 3, 4]
1 |
my_list=’foo’,’bar’ my_list+=cmd+numbers print(my_list) # [‘foo’, ‘bar’, ‘ls’, ‘/some/dir’, 0, 1, 2, 3, 4] |
Оба этих метода определенно работают, и до того, как я узнал о chain, я бы выбрал второе направление, но я думаю, что chain более прямой и простой способ понимания решения данного случая.
Other Set Operations
We can test if an item exists in a set or not, using the keyword.
Output
True False
Built-in Functions with Set
Built-in functions like , , , , , , , etc. are commonly used with sets to perform different tasks.
Function | Description |
---|---|
all() | Returns if all elements of the set are true (or if the set is empty). |
any() | Returns if any element of the set is true. If the set is empty, returns . |
enumerate() | Returns an enumerate object. It contains the index and value for all the items of the set as a pair. |
len() | Returns the length (the number of items) in the set. |
max() | Returns the largest item in the set. |
min() | Returns the smallest item in the set. |
sorted() | Returns a new sorted list from elements in the set(does not sort the set itself). |
sum() | Returns the sum of all elements in the set. |
Removing elements from a set
A particular item can be removed from a set using the methods and .
The only difference between the two is that the function leaves a set unchanged if the element is not present in the set. On the other hand, the function will raise an error in such a condition (if element is not present in the set).
The following example will illustrate this.
Output
{1, 3, 4, 5, 6} {1, 3, 5, 6} {1, 3, 5} {1, 3, 5} Traceback (most recent call last): File "<string>", line 28, in <module> KeyError: 2
Similarly, we can remove and return an item using the method.
Since set is an unordered data type, there is no way of determining which item will be popped. It is completely arbitrary.
We can also remove all the items from a set using the method.
Output
{'H', 'l', 'r', 'W', 'o', 'd', 'e'} H {'r', 'W', 'o', 'd', 'e'} set()
Other Python Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects:
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all elements from the set |
copy() | Returns a copy of the set |
difference() | Returns the difference of two or more sets as a new set |
difference_update() | Removes all elements of another set from this set |
discard() | Removes an element from the set if it is a member. (Do nothing if the element is not in set) |
intersection() | Returns the intersection of two sets as a new set |
intersection_update() | Updates the set with the intersection of itself and another |
isdisjoint() | Returns if two sets have a null intersection |
issubset() | Returns if another set contains this set |
issuperset() | Returns if this set contains another set |
pop() | Removes and returns an arbitrary set element. Raises if the set is empty |
remove() | Removes an element from the set. If the element is not a member, raises a |
symmetric_difference() | Returns the symmetric difference of two sets as a new set |
symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
union() | Returns the union of sets in a new set |
update() | Updates the set with the union of itself and others |