Count the number of times two values appear in a Python 3 iterator type element at the same time

Code that counts the number of times two elements in an iterator type (list or tuple) appear at the same time. It is also sample code for a combination of iterator-type elements (ʻitertools.combination), an immutable set (frozenset), and a keyed sorted`.

code

count_colocation2.py


import itertools
import typing
from itertools import chain


def count_colocation2(
        iteriter: typing.Iterable
        ) -> typing.Dict[frozenset, int]:
    """
Count the number of times two elements in an iterator type (list or tuple) appear at the same time.
    """
    if not isinstance(iteriter, typing.Iterable):
        raise TypeError()
    #Prepare the combination
    comb = itertools.combinations(frozenset(chain.from_iterable(iteriter)), 2)
    comb = [frozenset(item) for item in comb]
    #Check in order and add the number of combinations
    d = {key: 0 for key in comb}
    for entry in iteriter:
        for pair in comb:
            t = tuple(pair)
            if t[0] in entry and t[1] in entry:
                d[pair] += 1
    return d

1.py


from pprint import pp

from count_colocation2 import count_colocation2

ll = [
        ["a", "b", "c"],
        ["d", "e", "f"],
        ["a", "d", "f"],
        ["b", "d", "f"],
    ]

coloc2 = count_colocation2(ll)
#Sort values in descending order
pp(sorted(coloc2.items(), key=lambda item: item[1], reverse=True))

"""
[(frozenset({'f', 'd'}), 3),
 (frozenset({'f', 'e'}), 1),
 (frozenset({'f', 'b'}), 1),
 (frozenset({'f', 'a'}), 1),
 (frozenset({'d', 'e'}), 1),
 (frozenset({'d', 'b'}), 1),
 (frozenset({'d', 'a'}), 1),
 (frozenset({'b', 'a'}), 1),
 (frozenset({'b', 'c'}), 1),
 (frozenset({'a', 'c'}), 1),
 (frozenset({'f', 'c'}), 0),
 (frozenset({'b', 'e'}), 0),
 (frozenset({'e', 'a'}), 0),
 (frozenset({'e', 'c'}), 0),
 (frozenset({'d', 'c'}), 0)]
"""

Remarks

frozenset frozenset is an immutable version of set. You can change the contents of set with ʻadd or ʻupdate, but you cannot change the contents of frozen set. On the other hand, frozenset can be used as a dictionary key because it can get a hash.

#Uncommenting the next line will result in an error.
# print(hash(set(["a", "b", "c"])))
# TypeError: unhashable type: 'set'

#It completes normally.
print(hash(frozenset(["a", "b", "c"])))

There is tuple in the immutable type that can be the key of the same dictionary. tuple distinguishes the order of the elements, but flozenset does not.

typing.Sequencetyping.Iterable Python has classes like list, tuple, set, frozenset, but these can be categorized by common functionality. list and tuple are classified as sequence type (typing.Sequence) because they can be accessed by index. Also, list, tuple, set, and frozenset are classified as typing.Iterable because they provide iterators.

typing.Sequence and typing.Iterable are defined as types and can be used in type hints, as well as in ʻis instance and ʻis subclass.

List of iterator-type combination tuples

ʻItertools.combinations allows you to create a list of any number of combinatorial tuples from iterator type (typing.Iterable`) elements.

Access to the elements of set / frozen set

set / frozenset is not accessible at index [index]. You can access it by converting it to list or tuple once with list () or tuple (). Since it is an iterator type, for can be used.

Non-destructive sorting of dictionaries

You can specify a lambda expression for key = ... in sorted () to sort the dictionary non-destructively. Note that the dictionary key / value pairs are retrieved with dict.items (). If you pass dict itself to sorted, the key name will be the target of sorted ().

Sort by key


sorted(dict.items(), key=lambda item: item[0])                #ascending order
sorted(dict.items(), key=lambda item: item[0], reverse=True)  #descending order

Sort by value


sorted(dict.items(), key=lambda item: item[1])                #ascending order
sorted(dict.items(), key=lambda item: item[1], reverse=True)  #descending order

Recommended Posts

Count the number of times two values appear in a Python 3 iterator type element at the same time
Get a datetime instance at any time of the day in Python
Turn multiple lists with a for statement at the same time in Python
How to identify the element with the smallest number of characters in a Python list?
How to count the number of occurrences of each element in the list in Python with weight
"A book to train programming skills to fight in the world" Python code answer example --1.2 Count the number of the same characters
Get the number of specific elements in a python list
[Homology] Count the number of holes in data with Python
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
Count the number of Thai and Arabic characters well in Python
A function that measures the processing time of a method in python
Get the number of readers of a treatise on Mendeley in Python
python memo: enumerate () -get index and element of list at the same time and turn for statement
[python] [meta] Is the type of python a type?
Check the in-memory bytes of a floating point number float in Python
[Python] How to open two or more files at the same time
4 methods to count the number of occurrences of integers in a certain interval (including imos method) [Python implementation]
plot the coordinates of the processing (python) list and specify the number of times in draw ()
Get the caller of a function in Python
How to count the number of elements in Django and output to a template
[Python] Precautions when finding the maximum and minimum values in a numpy array with a small number of elements
Make a copy of the list in Python
Test the number of times you have thrown a query (sql) in django
Find the number of days in a month
Compare the sum of each element in two lists with the specified value in Python
Type conversion of multiple columns of pandas DataFrame with astype at the same time
Loop variables at the same time in the template
Output in the form of a python array
At the time of python update on ubuntu
How to get a list of files in the same directory with python
Get the value of a specific key in a list from the dictionary type in the list with Python
[Python] A program that finds the shortest number of steps in a game that crosses clouds
[Python] Representing the number of complaints from life insurance companies in a bar graph
Check the processing time and the number of calls for each process in python (cProfile)
Check if the string is a number in python
[Python] A program that counts the number of valleys
How to get the number of digits in Python
Count the number of parameters in the deep learning model
Get the size (number of elements) of UnionFind in Python
Tasks at the start of a new python project
Display a histogram of image brightness values in python
A reminder about the implementation of recommendations in Python
I created a Discord bot on Docker that reports the number of corona infected people in Tokyo at a specified time.
How to quickly count the frequency of appearance of characters from a character string in Python?
Python built-in function ~ divmod ~ Let's get the quotient and remainder of division at the same time
Find out the apparent width of a string in python
Make a table of multiplication of each element in a spreadsheet (Python)
Different from the import type of python. from A import B meaning
Grep so that grep does not appear at the time of grep
Count the number of characters in the text on the clipboard on mac
Python --Find out number of groups in the regex expression
[Note] Import of a file in the parent directory in Python
Get the number of occurrences for each element in the list
Find the eigenvalues of a real symmetric matrix in Python
Get the index of each element of the confusion matrix in Python
A Python script that compares the contents of two directories
Python --Check type of values
Put the process to sleep for a certain period of time (seconds) or more in Python
I compared the calculation time of the moving average written in Python
[Python 3.8 ~] Rewrite arrays etc. at the same time as definition [tips]
[Python] Let's reduce the number of elements in the result in set operations