Python language типы коллекций

пример

В Python существует несколько типов коллекций. Хотя типы, такие как и содержат одно значение, типы коллекции содержат несколько значений.

Списки

Тип вероятно, является наиболее часто используемым типом коллекции в Python. Несмотря на свое имя, список больше похож на массив на других языках, в основном на JavaScript. В Python список представляет собой просто упорядоченный набор действительных значений Python. Список может быть создан путем включения значений, разделенных запятыми, в квадратных скобках:

Список может быть пустым:

Элементы списка не ограничены одним типом данных, что имеет смысл, учитывая, что Python является динамическим языком:

Список может содержать другой список:

Элементы списка могут быть доступны через индекс или числовое представление их позиции. Списки в Python имеют нулевое индексирование, означающее, что первый элемент в списке имеет индекс 0, второй элемент — в индексе 1 и так далее:

Индексы также могут быть отрицательными, что означает подсчет с конца списка ( — индекс последнего элемента). Итак, используя список из приведенного выше примера:

Списки изменяются, поэтому вы можете изменить значения в списке:

Кроме того, можно добавлять и / или удалять элементы из списка:

Добавить объект в конец списка с помощью , возвращает .

Добавьте новый элемент для отображения по определенному индексу.

Удалите первое вхождение значения с , возвращает

Получить индекс в списке первого элемента, значение которого равно x. Он покажет ошибку, если такого элемента нет.

Подсчитать длину списка

подсчет количества элементов в списке

Изменить список

Удалите и верните элемент по индексу (по умолчанию последний элемент) с , возвращает элемент

Вы можете перебирать элементы списка, как показано ниже:

Кортеж

похож на список, за исключением того, что он является фиксированным и неизменным. Таким образом, значения в кортеже не могут быть изменены, а значения не будут добавлены или исключены из кортежа. Кортежи обычно используются для небольших коллекций значений, которые не нужно изменять, например, IP-адрес и порт. Кортежи представлены скобками вместо квадратных скобок:

Те же правила индексирования списков также применяются к кортежам. Кортежи также могут быть вложенными, и значения могут быть действительными действительными действительными Python.

Кортеж с одним членом должен быть определен (обратите внимание на запятую) следующим образом:

или же

или просто используя синтаксис

Словари

в Python представляет собой набор пар ключ-значение. Словарь окружен фигурными фигурными скобками. Каждая пара разделяется запятой, а ключ и значение разделяются двоеточием. Вот пример:

Чтобы получить значение, обратитесь к нему по его ключу:

Вы также можете получить все ключи в словаре, а затем перебрать их:

Словари сильно напоминают синтаксис JSON. модуль в стандартной библиотеке Python может использоваться для преобразования между JSON и словарями.

задавать

представляет собой набор элементов без повторов и без порядка вставки, но отсортированный порядок

Они используются в ситуациях, когда важно, чтобы некоторые вещи были сгруппированы вместе, а не какой порядок они были включены. Для больших групп данных гораздо быстрее проверить, находится ли элемент в чем он должен делать то же самое для

Определение очень похоже на определение :

Или вы можете построить используя существующий :

Проверьте членство в с использованием :

Вы можете перебирать точно так же, как и список, но помните: значения будут в произвольном порядке реализации.

defaultdict

— это словарь со значением по умолчанию для ключей, поэтому ключи, для которых не было явно определено значение, могут быть доступны без ошибок. особенно полезен, когда значения в словаре представляют собой коллекции (списки, dicts и т. д.) в том смысле, что его не нужно инициализировать каждый раз, когда используется новый ключ.

Значение никогда не вызовет KeyError. Любой ключ, который не существует, возвращает значение по умолчанию.

Например, рассмотрим следующий словарь

Если мы попытаемся получить доступ к несуществующему ключу, python возвращает нам ошибку следующим образом

Давайте попробуем с . Его можно найти в модуле коллекций.

То, что мы здесь сделали, — установить значение по умолчанию ( Boston ), если ключ-ключ не существует. Теперь заселите диктофон, как раньше:

Если мы попытаемся получить доступ к dict с несуществующим ключом, python вернет нам значение по умолчанию, то есть Boston

и возвращает созданные значения для существующего ключа, как обычный

Previous
Next

Other Useful Items

  • Looking for 3rd party Python modules? The
    Package Index has many of them.
  • You can view the standard documentation
    online, or you can download it
    in HTML, PostScript, PDF and other formats. See the main
    Documentation page.
  • Information on tools for unpacking archive files
    provided on python.org is available.
  • Tip: even if you download a ready-made binary for your
    platform, it makes sense to also download the source.
    This lets you browse the standard library (the subdirectory Lib)
    and the standard collections of demos (Demo) and tools
    (Tools) that come with it. There’s a lot you can learn from the
    source!
  • There is also a collection of Emacs packages
    that the Emacsing Pythoneer might find useful. This includes major
    modes for editing Python, C, C++, Java, etc., Python debugger
    interfaces and more. Most packages are compatible with Emacs and
    XEmacs.

Maximum Line Length

Limit all lines to a maximum of 79 characters.

For flowing long blocks of text with fewer structural restrictions
(docstrings or comments), the line length should be limited to 72
characters.

Limiting the required editor window width makes it possible to have
several files open side-by-side, and works well when using code
review tools that present the two versions in adjacent columns.

The default wrapping in most tools disrupts the visual structure of the
code, making it more difficult to understand. The limits are chosen to
avoid wrapping in editors with the window width set to 80, even
if the tool places a marker glyph in the final column when wrapping
lines. Some web based tools may not offer dynamic line wrapping at all.

Some teams strongly prefer a longer line length. For code maintained
exclusively or primarily by a team that can reach agreement on this
issue, it is okay to increase the line length limit up to 99 characters,
provided that comments and docstrings are still wrapped at 72
characters.

The Python standard library is conservative and requires limiting
lines to 79 characters (and docstrings/comments to 72).

The preferred way of wrapping long lines is by using Python’s implied
line continuation inside parentheses, brackets and braces. Long lines
can be broken over multiple lines by wrapping expressions in
parentheses. These should be used in preference to using a backslash
for line continuation.

Backslashes may still be appropriate at times. For example, long,
multiple with-statements cannot use implicit continuation, so
backslashes are acceptable:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

(See the previous discussion on for further
thoughts on the indentation of such multiline with-statements.)

Another such case is with assert statements.

Process Time

The process time cannot be set. It is not monotonic: the clocks stop
while the process is idle.

Name C Resolution Include Sleep Include Suspend
GetProcessTimes() 100 ns No No
CLOCK_PROCESS_CPUTIME_ID 1 ns No No
getrusage(RUSAGE_SELF) 1 µs No No
times() No No
clock() Yes on Windows, No otherwise No

The «C Resolution» column is the resolution of the underlying C
structure.

Examples of clock resolution on x86_64:

Name Operating system OS Resolution Python Resolution
CLOCK_PROCESS_CPUTIME_ID Linux 3.3 1 ns 1 ns
CLOCK_PROF FreeBSD 8.2 10 ms 1 µs
getrusage(RUSAGE_SELF) FreeBSD 8.2 1 µs
getrusage(RUSAGE_SELF) SunOS 5.11 1 µs
CLOCK_PROCESS_CPUTIME_ID Linux 3.0 1 ns 1 µs
getrusage(RUSAGE_SELF) Mac OS 10.6 5 µs
clock() Mac OS 10.6 1 µs 5 µs
CLOCK_PROF OpenBSD 5.0 5 µs
getrusage(RUSAGE_SELF) Linux 3.0 4 ms
getrusage(RUSAGE_SELF) OpenBSD 5.0 8 ms
clock() FreeBSD 8.2 8 ms 8 ms
clock() Linux 3.0 1 µs 10 ms
times() Linux 3.0 10 ms 10 ms
clock() OpenBSD 5.0 10 ms 10 ms
times() OpenBSD 5.0 10 ms 10 ms
times() Mac OS 10.6 10 ms 10 ms
clock() SunOS 5.11 1 µs 10 ms
times() SunOS 5.11 1 µs 10 ms
GetProcessTimes() Windows Seven 16 ms 16 ms
clock() Windows Seven 1 ms 1 ms

The «OS Resolution» is the resolution announced by the operating
system.
The «Python Resolution» is the smallest difference between two calls
to the time function computed in Python using the clock_resolution.py
program.

Accessing Counts¶

Once a Counter is populated, its values can be retrieved
using the dictionary API.

import collections

c = collections.Counter('abcdaab')

for letter in 'abcde'
    print '%s%d' % (letter, cletter])

Counter does not raise
for unknown items. If a value has not been seen in the input (as with
e in this example), its count is .

$ python collections_counter_get_values.py

a : 3
b : 2
c : 1
d : 1
e : 0

The elements() method returns an iterator that produces all of
the items known to the Counter.

import collections

c = collections.Counter('extremely')
c'z' = 
print c
print list(c.elements())

The order of elements is not guaranteed, and items with counts less
than zero are not included.

$ python collections_counter_elements.py

Counter({'e': 3, 'm': 1, 'l': 1, 'r': 1, 't': 1, 'y': 1, 'x': 1, 'z': 0})

Use most_common() to produce a sequence of the n most
frequently encountered input values and their respective counts.

import collections

c = collections.Counter()
with open('/usr/share/dict/words', 'rt') as f
    for line in f
        c.update(line.rstrip().lower())

print 'Most common:'
for letter, count in c.most_common(3):
    print '%s%7d' % (letter, count)

This example counts the letters appearing in all of the words in the
system dictionary to produce a frequency distribution, then prints the
three most common letters. Leaving out the argument to
most_common() produces a list of all the items, in order of
frequency.

deque 对象¶

class (iterable, maxlen)

返回一个新的双向队列对象,从左到右初始化(用方法 ) ,从 iterable (迭代对象) 数据创建。如果 iterable 没有指定,新队列为空。

Deque队列是由栈或者queue队列生成的(发音是 “deck”,”double-ended queue”的简称)。Deque 支持线程安全,内存高效添加(append)和弹出(pop),从两端都可以,两个方向的大概开销都是 O(1) 复杂度。

虽然 对象也支持类似操作,不过这里优化了定长操作和 和 的开销。它们引起 O(n) 内存移动的操作,改变底层数据表达的大小和位置。

如果 maxlen 没有指定或者是 ,deques 可以增长到任意长度。否则,deque就限定到指定最大长度。一旦限定长度的deque满了,当新项加入时,同样数量的项就从另一端弹出。限定长度deque提供类似Unix filter 的功能。它们同样可以用与追踪最近的交换和其他数据池活动。

双向队列(deque)对象支持以下方法:

(x)

添加 x 到右端。

(x)

添加 x 到左端。

()

移除所有元素,使其长度为0.

()

创建一份浅拷贝。

3.5 新版功能.

(x)

计算 deque 中元素等于 x 的个数。

3.2 新版功能.

(iterable)

扩展deque的右侧,通过添加iterable参数中的元素。

(iterable)

扩展deque的左侧,通过添加iterable参数中的元素。注意,左添加时,在结果中iterable参数中的顺序将被反过来添加。

(x, start, stop)

返回 x 在 deque 中的位置(在索引 start 之后,索引 stop 之前)。 返回第一个匹配项,如果未找到则引发 。

3.5 新版功能.

(i, x)

在位置 i 插入 x 。

如果插入会导致一个限长 deque 超出长度 maxlen 的话,就引发一个 。

3.5 新版功能.

()

移去并且返回一个元素,deque 最右侧的那一个。 如果没有元素的话,就引发一个 。

()

移去并且返回一个元素,deque 最左侧的那一个。 如果没有元素的话,就引发 。

(value)

移除找到的第一个 value。 如果没有的话就引发 。

()

将deque逆序排列。返回 。

3.2 新版功能.

(n=1)

向右循环移动 n 步。 如果 n 是负数,就向左循环。

如果deque不是空的,向右循环移动一步就等价于 , 向左循环一步就等价于 。

Deque对象同样提供了一个只读属性:

Deque的最大尺寸,如果没有限定的话就是 。

3.1 新版功能.

除了以上操作,deque 还支持迭代、封存、、、、、成员检测运算符 以及下标引用例如通过 访问首个元素等。 索引访问在两端的复杂度均为 O(1) 但在中间则会低至 O(n)。 如需快速随机访问,请改用列表。

Deque从版本3.5开始支持 , , 和 。

示例:

>>> from collections import deque
>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d                   # iterate over the deque's elements
...     print(elem.upper())
G
H
I

>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque()

>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'
>>> list(d)                          # list the contents of the deque

>>> d                             # peek at leftmost item
'g'
>>> d-1                            # peek at rightmost item
'i'

>>> list(reversed(d))                # list the contents of a deque in reverse

>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque()
>>> d.rotate(1)                      # right rotation
>>> d
deque()
>>> d.rotate(-1)                     # left rotation
>>> d
deque()

>>> deque(reversed(d))               # make a new deque in reverse order
deque()
>>> d.clear()                        # empty the deque
>>> d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):
    File "<pyshell#6>", line 1, in -toplevel-
        d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque()

Copyright and License Information

Copyright (c) 2001-2020 Python Software Foundation. All rights reserved.

Copyright (c) 2000 BeOpen.com. All rights reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives. All
rights reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum. All rights reserved.

See the LICENSE for
information on the history of this software, terms & conditions for usage, and a
DISCLAIMER OF ALL WARRANTIES.

This Python distribution contains no GNU General Public License (GPL) code,
so it may be used in proprietary projects. There are interfaces to some GNU
code but these are entirely optional.

All trademarks referenced herein are property of their respective holders.

Counter with String

In Python, everything is an object and string is an object too. Python string can be created simply by enclosing characters in the double quote. Python does not support a character type. These are treated as strings of length one, also considered as a substring.

In the example below, a string is passed to Counter. It returns dictionary format, with key/value pair where the key is the element and value is the count. It also considers space as an element and gives the count of spaces in the string.

Example:

from collections import Counter
my_str = "Welcome to Guru99 Tutorials!"
print(Counter(my_str))

Output:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

FreeBSD timecounter

kern.timecounter.choice lists available hardware clocks with their
priority. The sysctl program can be used to change the timecounter.
Example:

# dmesg | grep Timecounter
Timecounter "i8254" frequency 1193182 Hz quality 0
Timecounter "ACPI-safe" frequency 3579545 Hz quality 850
Timecounter "HPET" frequency 100000000 Hz quality 900
Timecounter "TSC" frequency 3411154800 Hz quality 800
Timecounters tick every 10.000 msec
# sysctl kern.timecounter.choice
kern.timecounter.choice: TSC(800) HPET(900) ACPI-safe(850) i8254(0) dummy(-1000000)
# sysctl kern.timecounter.hardware="ACPI-fast"
kern.timecounter.hardware: HPET -> ACPI-fast

Available clocks:

  • «TSC»: Time Stamp Counter of the processor
  • «HPET»: High Precision Event Timer
  • «ACPI-fast»: ACPI Power Management timer (fast mode)
  • «ACPI-safe»: ACPI Power Management timer (safe mode)
  • «i8254»: PIT with Intel 8254 chipset

The commit 222222 (May
2011) decreased ACPI-fast timecounter quality to 900 and increased
HPET timecounter quality to 950: «HPET on modern platforms usually
have better resolution and lower latency than ACPI timer».

Get and set the count of Elements using Counter

To get the count of an element using Counter you can do as follows:

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
print(counter1) # this will give you the count of element 'y'

Output:

12

To set the count of the element you can do as follows:

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

print(counter1)

counter1 = 20
counter1 = 10

print(counter1)

Output:

12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})

Summary:

  • Counter is a container that will hold the count of each of the elements present in the container.
  • Counter is a sub-class available inside the dictionary class.
  • Using the Python Counter tool, you can count the key-value pairs in an object, also called a hashtable object.
  • The Counter holds the data in an unordered collection, just like hashtable objects. The elements here represent the keys and the count as values.
  • It allows you to count the items in an iterable list.
  • Arithmetic operations like addition, subtraction, intersection, and union can be easily performed on a Counter.
  • A Counter can also count elements from another counter.
  • The important methods available on a Counter are elements() , most_common(value), subtract() and update().
  • A counter can be used on a string, list, dictionary, and tuple.

Модуль Collections

Collections — это встроенный модуль Python, реализующий специализированный контейнер типов данных. Является альтернативой встроенным контейнерам общего назначения Python, таким как , , и .

Рассмотрим несколько структур данных, представленных в этом модуле:

Доступ к данным, хранящимся в обычном кортеже, можно получить с помощью индексов. Пример:

Не обязательно давать названия отдельным элементам, хранящимся в кортеже. В этом есть необходимость лишь в том случае, если кортеж обладает множеством полей.

Именно здесь функциональность namedtuple проявляет свои силы. Это функция для кортежей с именованными полями (Named Fields), которую можно рассматривать как расширение встроенного типа данных tuple. Именованные кортежи задают значение для каждой позиции в кортеже, делая код более читаемым и самодокументируемым. Доступ к объектам, хранящимся в кортеже, можно получить с помощью уникального (удобного для чтения) идентификатора. Это избавляет от необходимости запоминать целочисленные индексы. Рассмотрим его реализацию.

Построение namedtuple начинается с передачи названия объекта type (fruit). Затем передается строка с пробелами между названиям каждого поля. Теперь можно обращаться к различным параметрам:

Namedtuples — эффективная для памяти опция при определении неизменяемых полей в Python.

2. Counter

Counter — это подкласс dict, который используется для подсчета объектов hashable. Элементы хранятся в качестве ключей словаря, а количество объектов сохранено в качестве значения. Рассмотрим несколько примеров с Counter.

Со списками

С предложением

Помимо доступных для всех словарей методов, объекты Counter поддерживают еще три дополнительных:

elements()

Возвращает количество каждого элемента. В случае, если количество элемента меньше одного, метод не выполняется.

most_common()

Возвращает список наиболее повторяемых элементов и количество каждого из них. Количество элементов указывается в значении n. Если ни одно из значений не указано, возвращается количество всех элементов.

3. defaultdict

Словари — это эффективный способ хранения данных для дальнейшего извлечения, в котором данные представлены в виде неупорядоченного множества пар key:value. Ключи — это уникальные и неизменяемые объекты.

Все очень просто, когда значения представлены целыми числами или строками. Однако если они представлены в форме списков и словарей, значение (пустой список или словарь) нужно инициализировать при первом использовании ключа. defaultdict автоматизирует и упрощает этот процесс. Для лучшего понимания рассмотрим пример ниже:

Словарь Python выдает ошибку, поскольку ‘A’ на данный момент не находится в словаре. Рассмотрим тот же самый пример с использованием defaultdict.

создает элементы, для которых нужно получить доступ (если они еще не существуют). defaultdict также является объектом-словарем и содержит те же методы, что и словарь. Разница заключается в том, что он устанавливает первый аргумент (default_factory) в качестве типа данных по умолчанию для словаря.

4.OrderedDict

OrderedDict — это подкласс словаря, в котором хранится порядок добавления ключей. При итерации упорядоченного словаря элементы возвращаются в порядке добавления их ключей. Поскольку упорядоченный словарь запоминает порядок добавления, его можно использовать в сочетании с сортировкой для создания отсортированного словаря:

обычный словарь

словарь, отсортированный по значению

словарь, отсортированный по длине строки

Стоит отметить, что в Python 3.6 обычные словари отсортированы по добавлению, т. е. словари запоминают порядок добавления элементов.

Accessing, Initializing and Updating Counters

Initializing Counter

A Counter can be initialized by passing string value, list, dictionary, or tuple as shown below:

from collections import Counter
print(Counter("Welcome to Guru99 Tutorials!"))   #using string
print(Counter()) #using list
print(Counter({'x': 4, 'y': 2, 'z': 2})) #using dictionary
print(Counter(('x','y','z','x','x','x','y', 'z'))) #using tuple

You can also initialize a empty Counter as shown below:

from collections import Counter
_count = Counter()

Updating Counter

You can add values to the Counter by using update() method.

_count.update('Welcome to Guru99 Tutorials!')

The final code is :

from collections import Counter
_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print(_count)

The output is:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

Accessing Counter

To get the values from the Counter, you can do as follows:

from collections import Counter

_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print('%s : %d' % ('u', _count))
print('\n')
for char in 'Guru':
    print('%s : %d' % (char, _count))

Output:

u : 3

G : 1
u : 3
r : 2
u : 3

Arithmetic¶

Counter instances support arithmetic and set operations for
aggregating results.

import collections

c1 = collections.Counter()
c2 = collections.Counter('alphabet')

print 'C1:', c1
print 'C2:', c2

print '\nCombined counts:'
print c1 + c2

print '\nSubtraction:'
print c1 - c2

print '\nIntersection (taking positive minimums):'
print c1 & c2

print '\nUnion (taking maximums):'
print c1 | c2

Each time a new Counter is produced through an operation, any
items with zero or negative counts are discarded. The count for a
is the same in c1 and c2, so subtraction leaves it at
zero.

$ python collections_counter_arithmetic.py

C1: Counter({'b': 3, 'a': 2, 'c': 1})
C2: Counter({'a': 2, 'b': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})

Combined counts:
Counter({'a': 4, 'b': 4, 'c': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})

Subtraction:
Counter({'b': 2, 'c': 1})

Intersection (taking positive minimums):
Counter({'a': 2, 'b': 1})

Union (taking maximums):
Counter({'b': 3, 'a': 2, 'c': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})

Counter Methods

1. Get the count of individual elements

Individual element counts are accessed in the same way as that of a Dictionary, meaning that gives the count of .

>>> c = Counter(a=1, b=2, c=1)
>>> c
Counter({'b': 2, 'a': 1, 'c': 1})
>>> c
2
>>> c # Does not give KeyError, unlike a Dictionary
0

2. Set the count of elements

To set the count of an element, use . If does not exist, it gets added to the Counter Dictionary, along with the new count.

>>> c = Counter(a=1, b=2, c=1)
>>> c
Counter({'b': 2, 'a': 1, 'c': 1})
>>> c = 4
>>> c
Counter({'d': 4, 'b': 2, 'a': 1, 'c': 1})

To remove a key from the Counter object, use .

>>> del c
>>> c
Counter({'b': 2, 'a': 1, 'c': 1})

4. elements()

This method returns an iterator over the elements, values of which are repeated as many times as their counts. This method ignores all elements that have their counts less than one.

>>> c
Counter({'b': 2, 'a': 1, 'c': 1})
>>> c = -1
>>> c
>>> c.elements()
<itertools.chain object at 0x102e2a208>
>>> type(c.elements())
<class 'itertools.chain'>
>>> for i in c.elements():
...     print(i)
...
a
b
b
c
>>> list(c.elements())


>>> c = -1
>>> c
Counter({'b': 2, 'a': 1, 'c': 1, 'd': -1})
>>> # Ignores d since count < 1
>>> list(c.elements())

5. most_common(n)

This returns a list of the n most common elements and their counts from the most common to the least. If n is omitted or ,  returns all elements in the counter. Elements with equal counts are ordered arbitrarily.

>>> c
Counter({'b': 2, 'a': 1, 'c': 1, 'd': -1})
>>> c.most_common()

>>> c.most_common(2)

6. subtract(iterable/mapping)

This returns a mapping/iterable after subtracting the contents of the two iterables/mappings. Elements are not replaced, and only their counts are subtracted.

>>> a = Counter('redblue')
>>> a
Counter({'e': 2, 'r': 1, 'd': 1, 'b': 1, 'l': 1, 'u': 1})
>>> b = Counter('blueorange')
>>> b
Counter({'e': 2, 'b': 1, 'l': 1, 'u': 1, 'o': 1, 'r': 1, 'a': 1, 'n': 1, 'g': 1})

>>> # Subtracts b from a and updates a accordingly
>>> a.subtract(b)
>>> a
Counter({'d': 1, 'r': 0, 'e': 0, 'b': 0, 'l': 0, 'u': 0, 'o': -1, 'a': -1, 'n': -1, 'g': -1})

7. update(iterable/mapping)

This is similar to , but only adds counts instead of subtracting them.

>>> a = Counter('12321')
>>> b = Counter('23432')
>>> a
Counter({'1': 2, '2': 2, '3': 1})
>>> b
Counter({'2': 2, '3': 2, '4': 1})

>>> # Add counts into a
>>> a.update(b)
>>> a
Counter({'2': 4, '3': 3, '1': 2, '4': 1})
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *