Make a table of multiplication of each element in a spreadsheet (Python)

Prerequisites

You want to write the following Python dictionary values in a spreadsheet in the form of a table.

    pattern = {
        'area': ['Japan', 'America', 'England'],
        'sex': ['Man', 'woman'],
        'height': ['100 cm or more', 'Less than 100 cm']
    }

environment

Creation of multiplication table (direct product)

If you want to create a table that multiplies the following elements in a spreadsheet,

area sex height
1 Japan Man 100 cm or more
2 Japan Man Less than 100 cm
3 Japan woman 100 cm or more
4 Japan woman Less than 100 cm
5 America Man 100 cm or more
6 America Man Less than 100 cm
7 America woman 100 cm or more
8 America woman Less than 100 cm
9 England Man 100 cm or more
10 England Man Less than 100 cm
11 England woman 100 cm or more
12 England woman Less than 100 cm

If you write the following in Python, comma-separated ones will be output.

from itertools import product

if __name__ == '__main__':
    pattern = {
        'area': ['Japan', 'America', 'England'],
        'sex': ['Man', 'woman'],
        'height': ['100 cm or more', 'Less than 100 cm']
    }
    delimiter = ','
    result = delimiter + delimiter.join(pattern.keys()) + '\n'
    i = 0
    for item in product(*pattern.values()):
        i += 1
        result += str(i) + delimiter + delimiter.join(item) + '\n'
    print(result)

Paste it into a spreadsheet to create a nice table.

,area,sex,height
1,Japan,Man,100 cm or more
2,Japan,Man,Less than 100 cm
3,Japan,woman,100 cm or more
4,Japan,woman,Less than 100 cm
5,America,Man,100 cm or more
6,America,Man,Less than 100 cm
7,America,woman,100 cm or more
8,America,woman,Less than 100 cm
9,England,Man,100 cm or more
10,England,Man,Less than 100 cm
11,England,woman,100 cm or more
12,England,woman,Less than 100 cm

Supplement

Creation of classification item table

If you want to create the following table for each item and its value in the above multiplication table

item value
area Japan
America
England
sex Man
woman
height 100 cm or more
Less than 100 cm

If you write the following in Python, comma-separated ones will be output.

if __name__ == '__main__':
    pattern = {
        'area': ['Japan', 'America', 'England'],
        'sex': ['Man', 'woman'],
        'height': ['100 cm or more', 'Less than 100 cm']
    }
    delimiter = ','
    result = ''
    for key, value in pattern.items():
        for index, item in enumerate(value):
            if index == 0:
                result += key
            result += delimiter + item + '\n'
    print(result)

Paste it into a spreadsheet to create a nice table.

area,Japan
,America
,England
sex,Man
,woman
height,100 cm or more
,Less than 100 cm

Summarized code

If this is made into one Python file that can be advanced interactively, it will be as follows.

from itertools import product

def get_input(default: str = ''):
    value: str = input().rstrip("\n")
    if value:
        return value
    return default

def configure():
    print("""
Please configure
    delimiter [,]:
""")
    delimiter = get_input(',')

    print(f"""
    prefix:
    """)
    prefix = get_input()

    print(f"""
    suffix:
    """)
    suffix = get_input()
    return delimiter, prefix, suffix

def print_product_table(pattern: dict, delimiter: str, prefix: str, suffix: str):
    result = prefix + delimiter + delimiter.join(pattern.keys()) + suffix + '\n'
    i = 0
    for item in product(*pattern.values()):
        i += 1
        result += prefix + str(i) + delimiter + delimiter.join(item) + suffix + '\n'
    print(result)

def print_category_key_value(pattern, delimiter, prefix, suffix):
    result = ''
    for key, value in pattern.items():
        for index, item in enumerate(value):
            line = prefix
            if index == 0:
                line += key
            line += delimiter + item + suffix
            result += line.strip() + '\n'
    print(result)

if __name__ == '__main__':
    pattern = {
        'area': ['Japan', 'America', 'England'],
        'sex': ['Man', 'woman'],
        'height': ['100 cm or more', 'Less than 100 cm']
    }

    print_pattern: int = None
    while True:
        print("""
Print dict structure.

Enter print pattern:
    1. Product table
    2. Category key-value
        """)
        print_pattern = int(get_input())
        if print_pattern in [1, 2]:
            break;

    delimiter, prefix, suffix = configure()

    if print_pattern == 1:
        print_product_table(pattern, delimiter, prefix, suffix)
    elif print_pattern == 2:
        print_category_key_value(pattern, delimiter, prefix, suffix)

Other

Why Python
Because I was working with Python at that time.

Recommended Posts

Make a table of multiplication of each element in a spreadsheet (Python)
Make a copy of the list in Python
Make a joyplot-like plot of R in python
Make a bookmarklet in Python
Get the index of each element of the confusion matrix in Python
How to determine the existence of a selenium element in Python
Display a list of alphabets in Python 3
Make a relation diagram of Python module
How to display multiplication table in python
Let's make a combination calculation in Python
Status of each Python processing system in 2020
Get the caller of a function in Python
Match the distribution of each group in Python
[Memo] I tried a pivot table in Python
Rewriting elements in a loop of lists (Python)
Make a rock-paper-scissors game in one line (python)
Output in the form of a python array
Get a glimpse of machine learning in Python
A well-prepared record of data analysis in Python
Compare the sum of each element in two lists with the specified value in Python
Make each PowerPoint page an image file in Python
Make a copy of a Google Drive file from Python
A collection of code often used in personal Python
Make a simple Slackbot with interactive button in python
Until you insert data into a spreadsheet in Python
Group by consecutive elements of a list in Python
Display a histogram of image brightness values in python
A collection of Excel operations often used in Python
A reminder about the implementation of recommendations in Python
How to identify the element with the smallest number of characters in a Python list?
Output the specified table of Oracle database in Python to Excel for each file
How to count the number of occurrences of each element in the list in Python with weight
Take a screenshot in Python
Create a function in Python
Create a dictionary in Python
[Python] How to make a list of character strings character by character
Check the operation of Python for .NET in each environment
Get the number of specific elements in a python list
[Python] How to delete rows and columns in a table (list of drop method options)
Let's make a spot sale service 4 (in Python mini Hack-a-thon)
Equivalence of objects in Python
Matrix multiplication in python numpy
Don't make test.py in Python!
How to develop in a virtual environment of Python [Memo]
[Note] Import of a file in the parent directory in Python
Make a fortune with Python
Make Opencv available in Python
How to get a list of built-in exceptions in python
[python] Manage functions in a dictionary (command table, function table, function pointer)
Make python segfault in 2 lines
Get the number of occurrences for each element in the list
A memo of writing a basic function in Python using recursion
I tried to make a stopwatch using tkinter in python
Draw a heart in Python
Implementation of quicksort in Python
A set of script files that do wordcloud in Python3
Find the eigenvalues of a real symmetric matrix in Python
I want to make input () a nice complement in python
When I got a list of study sessions in Python, I found something I wanted to make
[Python] A program that compares each element of list one by one and wins or loses. zip ()
[Python] A memo of frequently used phrases (by myself) in Python scripts