Python notes to forget soon

About this memo

Python is a popular language, and even if you google it, it's noisy, so you have to put it together yourself. Even if there is one more noise.

How to google

You can easily reach Official Documents by googled with python docs What you want to find out.

Basic

A level that allows you to fight with the D rank of the paiza skill check.

Input / output

Output value to stdout

https://docs.python.org/ja/3/library/functions.html#print

#In the case of numerical value
print(123)

#For strings
print("thanks")

--Objects other than strings are also converted to strings --Last line break

Get one line of string from stdin

https://docs.python.org/ja/3/library/functions.html#input

s = input()

--The trailing line break is removed

Basic type

https://docs.python.org/ja/3/tutorial/introduction.html#numbers https://docs.python.org/ja/3/tutorial/datastructures.html#tuples-and-sequences


n = 123   #integer
f = 123.4 #Decimal

s1 = 'String' # string (When specifying with single quotes)
s2 = "String" # string (When specifying with double quotes)

ln = [1, 2, 3]  #list
lx = [1, "two"] #Different types can be mixed

d = { "a": 1, "b": 2, "c": 3 } #Dictionary type(Things commonly called Hash, Map, or Dict)

t = (1, "two") #Tuple(Tuple)

#Boolean value
b1 = True
b2 = False

#Null or nil-like things
null = None

--You can use either single-quoted or double-quoted strings. --Note that if you use {a: 1} as the dictionary key without quotes instead of {"a ": 1}, the value of variable a will be used as the key. --Access to tuple elements can be accessed with t [0], just like lists.

Type conversion

Convert string to integer

https://docs.python.org/ja/3/library/functions.html#int

i = int("123")

Convert object to string

https://docs.python.org/ja/3/library/functions.html#func-str

s = str(123)

Conditional branch

if statement

https://docs.python.org/ja/3/tutorial/controlflow.html#if-statements

name = input()

if name == "Anchan":
  print("Noble, seriously painful, this is Forever ...")
elif name == "Mi-chan":
  print("Too thin")
else:
  print("I really quit ...!") 

--If you do not add : after each line of ʻif ..., ʻelif ..., ʻelse, an error will occur. --Blocks should be indented with spaces instead of being enclosed in {} etc. --ʻElif and ʻelse parts can be omitted --ʻElif part can be written multiple times --Note that it is ʻelif, not ʻelse if or ʻelse if. --Since Python is not a ʻif expression but a ʻif statement, you cannot directly assign the result of a conditional branch to a variable (unlike a language with a ʻif expression).

loop

for statement

https://docs.python.org/ja/3/tutorial/controlflow.html#for-statements

ns = [1, 2, 3]

for n in ns:
  print(n)

--An error will occur if you do not add : after for ... in ... --Blocks should be indented with spaces instead of being enclosed in {} etc.

String processing

Divide the string with spaces to make a list

https://docs.python.org/ja/3/library/stdtypes.html#str.split

source = "Pecoline Coccolo Cal"

names = source.split()

Beginner

function

Definition

def f(a, b, c):
  return a + b + c

--def followed by function name, argument list, : --If you do not write return, it will not be a return value --Blocks are indented with spaces --You can write multiple sentences

sqrt

import math

x = math.sqrt(2)

Text processing

Divide stdin with line breaks to make a" list of strings "

import sys

ts = sys.stdin.read().splitlines()

--It looks like you have to importthesys` module.

Change "List of strings" to "List of integers"

ns = map(int, ["1", "2", "3"])

--You can convert without problems even if there is a line break at the end of the character string --Since it is a map object, if you really want to list it, use the list function as the return value of map.

Change "List of integers" to "List of strings"

ss = map(str, [1, 2, 3])

--Since it is a map object, if you really want to list it, use the list function as the return value of map.

List processing

Change range to list

ns = list(range(10))

--It seems that you can convert list-like things with the list function.

Total of numbers

s = sum([1, 2, 3, 4, 5])

Intermediate

Functional

lambda expression (lambda expression)

#With 2 arguments
plus = lambda a, b: a + b

#With one argument
plus1 = lambda a: plus(1, a)

#With 0 arguments
hello = lambda: print("hello")

--return returns the return value without writing

unique

ns = list(set([1, 2, 2, 3]))

--It seems that it will be converted back to list after making it a set type and removing duplicates.

filter

#For example, when filtering by an even number
even = lambda n: n % 2 == 0
ns = filter(even, range(10))

concat, flatten

ns = sum([[1,2,3], [10, 20, 30]], [])

--By specifying the initial value in the second argument of the sum function, it looks like fold or reduce using+.

map

#For example, if you add 1 to each element
plus1 = lambda n: n + 1
ns = map(plus1, [1, 2, 10, 20, 100, 200])

reduce

from functools import reduce

ns = [1, 2, 3, 4, 5]

#Oreore sum
plus = lambda a, b: a + b
my_sum = reduce(plus, ns, 0)

#Oreore product
times = lambda a, b: a * b
my_product = reduce(times, ns, 1)

#Ore ole len
one = lambda _: 1
my_len = reduce(plus, map(one, ns), 0)

--Import reduce from the functools module

Recommended Posts

Python notes to forget soon
Python scraping notes
Updated to Python 2.7.9
Python study notes _000
Python learning notes
python notes: Modularization: __name__ == How to use'__main__'
Python beginner notes
Python study notes_006
python C ++ notes
Python study notes _005
Python grammar notes
Python Library notes
python personal notes
python pandas notes
Python study notes_001
python learning notes
Python3.4 installation notes
"Backport" to python 2
Python list comprehensions that are easy to forget
Personal notes to doc Python code in Sphinx
Knowledge notes needed to understand the Python framework
How to install Python
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Python package development notes
Rewrite Python2 code to Python3 (2to3)
How to install python
python decorator to retry
Introduction to Python language
python decorator usage notes
Python ipaddress package notes
Introduction to OpenCV (python)-(2)
[Personal notes] Python, Django
Python Pickle format notes
[Python] pytest-mock Usage notes
First Python miscellaneous notes
Note to daemonize python
Introducing Python 2.7 to CentOS 6.6
Matlab => Python migration notes
Connect python to mysql
[Python MinMaxScaler] Normalize to 0 ~ 1
Notes around Python3 assignments
Notes using Python subprocesses
Python try / except notes
Python framework bottle notes
Syntax that Perl users tend to forget in Python
Python --Notes when converting from str type to int type
Site notes to help you use NetworkX with Python
Python notes using perl-ternary operator
Connect to BigQuery with Python
Post from Python to Slack
How to install Python [Windows]
Post to vim → Python → Slack
Introduction to Python Django (2) Win
Introduction to Cython Writing [Notes]
To flush stdout in Python
Convert numpy int64 to python int
python3: How to use bottle (2)
O'Reilly python3 Primer Learning Notes
[Python] Convert list to Pandas [Pandas]
Web scraping notes in python3