O'Reilly python3 Primer Learning Notes

Overview

Learn python from O'Reilly's introduction to python. I write down what I learned in no particular order without categorizing it.

Use of radix

You can express the radix by adding a specific keyword before the number.

#Binary 0b
0b101 # 5

#Eighth number 0o
0o11 # 9

#Hexadecimal 0x
0x1a1 # 417

Use // by division

Division is usually "/", but you can use "//" to calculate decimal point truncation.

a = 3
a / 2 # 1.5
a // 2 # 1

Difference between "'" and "" "in character string creation

Basically either can be used. However, if you want to use either one in the text, enclose it in the quart of the one you do not use. Others If you escape with "", no error will occur even with the same quote as the box.

a = 'a'bc'd' #error
a = "a'bc'd" #No error
a = 'a\'bc\'d' #error

What is a literal?

A numerical value or character string written directly in the program. Antonym with a variable? .. You can leave the numbers as they are, but be sure to enclose the strings in quotes.

Repeating a string with "*"

Character strings can be repeated by using "*" and numbers when combining character strings

start = 'na' * 4
print(start) #nananana

Extraction of characters by []

If you want to extract a certain part of the character in the character string, add [order] to the character string variable and call it. If you add "-", the order is from the end.

code = 'abcdefg'
code[0] # a
code[-1] # g
code[-3] # e

Slice the string with []

You can select and extract a character string with character string [start: end: step]. Note that the counting method starts from 0, so it is the extraction up to the number -1 specified by end.

a = 'abcdefg'
a[:] #Slice everything'0123456789'
a[1:] #Slice everything from the first'bcdefg'
a[1:3] #Slice from 1st to 2nd'bc'
a[0:0] # ''
a[0:5:2] #Every 1 from 0th to 4th'ace'
a[:2] #From the beginning to the first'ab'
a[-3:] #3 characters from the end of the minute'gfe'
a[::2] #Without 1 from the beginning to the end'aceg'

Count the number of words in a string

a = 'abc'
len(a) # 3

Split a string into a list --split ()

You can split a string into a list with specific characters with split. If nothing is specified like split (), it is automatically split with a whitespace character. split is a string-specific built-in function. The method that the string object has?

a = 'ab,cd'
a.split(',') # ['ab','cd']
a = 'ab cd'
a.split() # ['ab','cd']

Join the list into a string --join ()

You can join the list with the join function. With'str'.join (list), put str in between and join the elements of list.

line = ['a','b','c']
'x',join(line) # 'axbxc'

String replacement --replace ()

You can replace a character string with character string .replace (replacement character string, character string after replacement, number of replacements). Replace all if the number of times is omitted

a = 'abc abc abc'
a.replace('abc','xxx',1) # 'xxx xxx abc'
a.replace('abc','xxx') # 'xxx xxx xxx'

Other string manipulation functions

a = '"This is a pen. That is a eraser"'

#Get the position where a string first appears- find()
a.find('pen') # 11

#Get the position where a string appears last- rfind()
a.rfind('is') # 21

#Calculate how many strings are included- count()
a.count('eraser') # 1
#Delete a specific string from both ends- strip()
a.strip('"') # 'This is a pen. That is a eraser'

Creating a list

Create a list with list () or []. If you list () a character string, it will be a character-by-character list.

a = list()
a # []Empty list
b = [] 
b # []Empty list
c = 'abc'
list(c) # ['a','b','c']

List slice

Like strings, lists can be extracted with [:].

a =  ['a','b','c']
#Get the elements of the 0th to 2nd exponent
a[0:2] # ['a','b']
#Get elements by skipping one from the beginning
a[::2] # ['a','c']

Add, remove, and more elements to the list

a =  ['a','b','c']
b = ['d','e','f']

#Join list- extend()
c = a.extend(b)
c # ['a','b','c','d','e','f']

#Add to the end of the element- append()
a.append('d')
a # ['a','b','c','d']

#Add element to specified position-insert()
b.insert(1,'x')
b # ['d','x','e','f']

#Delete by specifying a number- pop()
a.pop(1) 
a # ['a','c','d']

#Delete by specifying an element- remove()
a.remove('a') 
a # ['c','d']

#Examine the index of an element- index()
a.index('c') # 0

#Check for value in
a in c # true

List element sort --sort () sorted ()

sort () sorts the list itself specified as an argument. sorted () returns the sorted list as a return value. (The order of the list itself specified in the argument does not change)

a = [3,2,1]
b = [3,2,1]
#Sorting the list itself
sort(a)
a # [1,2,3]
c = sorted(b)
c # [1,2,3]
b # [3,2,1]

What is a tuple

A tuple is a constant list that cannot be changed or added after it has been defined.

#Creating tuples
a = ('a','b','c')

#Change array to tuple- tuple()
b = ['a','b','c']
c = tuple(b)
c # ('a','b','c')

Tuple unpack

Tuples allow you to assign multiple variables at once. This is called tuple unpacking.

a , b , c = (1, 2, 3)
a # 1
b # 2
c # 3

You can also use this to exchange variable values without using temporary variables.

a = 'cat'
b = 'dog'
a , b = b, a
a # 'dog'
b # 'cat'

What is a dictionary?

A list with keys that correspond to individual elements. Synonymous with associative array in php.

#Creating a dictionary
a = { 'cat' : 'Cat', 'dog' : 'dog' }
a['cat'] #Cat

#Creating an empty dictionary
a = {}

Convert to dictionary using dict ()

You can use dict () to convert various elements to dictionary type.

#Convert 2D list to dictionary
line = [['dog','dog'],['cat','Cat']]
dict(line) # {'dog': 'dog', 'cat': 'Cat'}

#Convert a list with two-character elements into a dictionary
line = ['ab', 'bd', 'cd', 'de']
dict(line) # {'a': 'b', 'c': 'd', 'd': 'e', 'b': 'd'}

Combine dictionaries-update

Dictionary types can be combined with the update function. At that time, if there is something with the same key, the element specified in the argument of update () has priority.

one = {'a': 'Ah','b':'I'}
two = {'c':'U','b':'O' }
one.update(two)
one # {'a': 'Ah', 'c': 'U', 'b': 'O'}

Delete dictionary elements --del, clear ()

 #Delete the element with the specified key
one = {'a': 'Ah','b':'I'}
del one['a']
one # {'b':'I'}

#Delete all elements
one = {'a': 'Ah','b':'I'}
one.clear()
one # {}

Collective acquisition of dictionary type values and keys

Since it returns from python3 as an object instead of an array, it is better to convert it to an array with list ()

one = {'a': 'Ah','b':'I'}

#Get all keys- keys()
list(one.keys()) # ['a','b']

#Get all values- values() 
list(one.values()) # ['Ah','I']

#Get all kye and values- items()
list(one.items()) # [('a':'Ah'),('b','I')]

How to write internal notation

#Squared list of numbers from 0 to 4
li = [i**2 for i in range(5)]

#I agree with the following
li = []
for i in range(5):
	li.append(i**2)

#Even number up to 100
li = [i for i in range(1,101) if i % 2 == 0]

#I agree with the following
li = []
for i in range(1,101):
	if i % 2 == 0:
		li.append(i)

yield and generator

If you use "yield" instead of return in a function, you can pause the process, save it, and then restart it. In the case of value retrieval by the for statement, the generator function can be used as it is, but when using next, it must be made into an object once.

#Creating a generator
def func() :
	sum = 0
	while True :
		sum += 7
		yield sum

#Extraction of value by next
sevens = func()
next(sevens) # 7
next(sevens) # 14
next(sevens) # 21
#Often objects.next()There is a description, but it cannot be used from python3.
#next()When using next as above(Object)
#object.__next__To describe

#Extracting a value with a for statement
for i in func()
	print(i,end=',')
	# func()Adds break condition for while infinite loop
	if i > 21
		break
#7,14,21,28,

Recommended Posts

O'Reilly python3 Primer Learning Notes
Python learning notes
python learning notes
Python data analysis learning notes
python learning
Python scraping notes
[Python] Learning Note 1
Python study notes _000
Notes on PyQ machine learning python grammar
Python beginner notes
python learning output
Learning notes from the beginning of Python 1
Python study notes_006
Python learning site
Python learning day 4
python C ++ notes
Python Deep Learning
Python study notes _005
Python grammar notes
Python Library notes
Python learning (supplement)
Deep learning × Python
First python [O'REILLY]
python personal notes
Learning notes from the beginning of Python 2
python pandas notes
Python study notes_001
Python3.4 installation notes
Python class (Python learning memo ⑦)
"Object-oriented" learning with python
Python module (Python learning memo ④)
missingintegers python personal notes
Reinforcement learning 1 Python installation
Python: Deep Learning Practices
Python ~ Grammar speed learning ~
Python: Unsupervised Learning: Basics
Python package development notes
Device mapper learning notes
python decorator usage notes
Python ipaddress package notes
Private Python learning procedure
[Personal notes] Python, Django
Learning Python with ChemTHEATER 02
Python Pickle format notes
[Python] pytest-mock Usage notes
Learning Python with ChemTHEATER 01
First Python miscellaneous notes
Python: Deep Learning Tuning
Matlab => Python migration notes
Python + Unity Reinforcement Learning (Learning)
Python: Supervised Learning (Regression)
Notes around Python3 assignments
Python Tkinter Primer Note
Notes using Python subprocesses
Python try / except notes
Python framework bottle notes
Python: Supervised Learning (Classification)
Python notes using perl-ternary operator
Python exception handling (Python learning memo ⑥)
Web scraping notes in python3
Learning flow for Python beginners