Learn python from O'Reilly's introduction to python. I write down what I learned in no particular order without categorizing it.
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
Division is usually "/", but you can use "//" to calculate decimal point truncation.
a = 3
a / 2 # 1.5
a // 2 # 1
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
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.
Character strings can be repeated by using "*" and numbers when combining character strings
start = 'na' * 4
print(start) #nananana
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
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'
a = 'abc'
len(a) # 3
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']
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'
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'
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'
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']
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']
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
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]
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')
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'
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 = {}
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'}
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 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 # {}
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')]
#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)
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