You will be an engineer in 100 days ――Day 30 ―― Python ―― Basics of Python language 6

This time too, it's a continuation of the basics of Python. It's already 30 days at the earliest. I don't feel like it's over www.

Click here for the last time [You will be an engineer in 100 days --Day 29 --Python --Basics of Python language 5] (https://qiita.com/otupy/items/22d4ab97b33c989ab284)

About built-in functions

I'm sorry if it doesn't appear

As a standard feature in python It has built-in functions.

I have been using it since the beginning of this course The print () function is also a built-in function.

Because it is an indispensable function for the program Let's learn how to use built-in functions.

** How to use the function **

Function name (argument, ...)

What is specified in () parentheses after the function name is called argument There may be multiple arguments depending on the function.

In that case, separate them with , commas. You can specify which argument it corresponds to.

The result of executing the function may return some value. This returned value is called the return value.

** Various built-in functions **

*** abs function ***

Returns the absolute value of the number. ʻAbs (numerical value) `

print(abs(2.5))
print(abs(-12.2))

2.5 12.2

** int function ** Change strings and decimal points to integer values. In the case of a character string, only numbers and only integers, decimal points are errors In the case of a numerical value, the part after the decimal point is rounded down.

print(int(12.3))
print(int('13'))
print(int(0.9))

12 13 0

*** float function ***

Change from a character or integer value to a floating point value. The letters must be numbers. Only decimal points and numbers are used.

float (string) float (integer value)

print(float(13))
print(float('15.5'))

13.0 15.5

*** oct function ***

Convert numbers to octal values ʻOct (numerical value) `

print(oct(8))
print(oct(2))

0o10 0o2

*** hex function ***

Convert a number to a hexadecimal string hex (numerical value)

print(hex(255))
print(hex(16))

0xff 0x10

0x is added in hexadecimal notation Starting from 0 and reaching 16, the digits are incremented.

If you want to convert hexadecimal numbers with or without the leading 0x This can be achieved using the format function.

print(format(255 , 'x'))
print(format(255 , 'X'))
print(format(255 , '#x'))

ff FF 0xff

*** input function ***

An input field comes out You can input to the program.

ʻInput ('string')`

s = input('--> ') 
print(s)

-> I entered

I entered

*** len function *** Returns the length of the object specified in the argument. len (object)

a = 'Hi, this is Matt Damon.'
#Returns the number of characters
print(len(a))

17

b = [1,2,3,4,5]
#Returns the number of elements in the list
print(len(b))

5

*** list function *** Convert the object specified in the argument to list type

list (object)

#Define dictionary type
d1 = {1:2,3:4,5:6}
print(d1)

#Convert key to list
print(list(d1.keys()))

#Convert values to list
print(list(d1.values()))

#Convert to a list with tuple-type elements of keys and values
print(list(d1.items()))

{1: 2, 3: 4, 5: 6} [1, 3, 5] [2, 4, 6] [(1, 2), (3, 4), (5, 6)]

*** dict function ***

Any combination of key and value can be converted to dictionary type.

dict (object)

#Convert a list with tuple-type elements into a dictionary
d2 = dict([('k1', 1), ('k2', 2), ('k3', 4)])
print(d2)

{'k1': 1, 'k2': 2, 'k3': 4}

*** max, min function ***

The max function returns the largest of the multiple specified objects. The min function is the opposite, returning the smallest value.

max (object) min (object)


sample_list = [1,2,3,4,5,6]
#Returns the maximum value
print(max(sample_list))
#Returns the minimum value
print(min(sample_list))

6 1

sample_st= 'apple'
#Returns the maximum value
print(max(sample_st))
#Returns the minimum value
print(min(sample_st))

p a

*** open function ***

A function that opens a file and creates a file object. This is just an introduction and will be explained in detail in a later lecture.

ʻOpen (file path)`

*** range function ***

Creates the number of objects specified in the argument.

range (number of times) range (start, end) range (start, end, interval)

#Generate 4 integers
print(list(range(4)))

[0, 1, 2, 3]

*** round function ***

Rounds the decimal point and returns the nearest integer. round (number)

print(round(3.499)) 
print(round(3.5))

3 4

When a digit is added to the second argument, it is rounded to the number of decimal places.

print(round(3.5187,3))
print(round(3.5187,1))

3.519 3.5

*** sorted function ***

Sorts the elements of the object specified in the argument. For details on how to use the sorted function, see the sorting lecture later. sorted (object)

*** str function *** Convert what is specified in the argument to a character string str (object)

#Convert an integer value to a string
print(str(12))

12

*** sum function ***

Returns the total value of list type elements. The element must be a number

li =[1,2,3,4]
print(sum(li))

10

*** zip function *** *** enumerate function ***

Details will be given in a later lecture.

Functions can be used in combination


#Converts a character to a decimal point and then converts it to an integer value to make it an absolute value.
print(abs(int(float('-3.14'))))

3

When combined, the one inside the parentheses is processed first.

In functions, it is common to use multiple combinations like this, The process becomes complicated and it becomes difficult to follow.

First, find the part that will be processed first, and is the result correct? I think it's better to follow that one by one.

enumerate function

I'm sorry if it doesn't appear

Well, I did the repeated writing with for sentence, do you remember? This is a review of how to write a for sentence.

In the for statement, the number of repetitions was specified using the range function and so on.


for i in range(5):
    print(i)

0 1 2 3 4

This will generate a number from 0 to 4 in the range function, As a for statement, the process is repeated 5 times.

The ʻenumeratefunction handles thisfor statement You can add avariable that counts the number of times`.

#Generate an integer from 5 to 9 and iterate.
for i , j in enumerate(range(5,10)):
    print(i , j)

0 5 1 6 2 7 3 8 4 9

When to use it is to count the number of times the process was performed It is often used when the process is exited by the number of times.


count = 0
for i in range(5):
    print(i)
    if i>=3:
        break
    count+=1

0 1 2 3


for i , j in enumerate(range(5)):
    print(i,j)
    if i>=3:
        break

0 0 1 1 2 2 3 3

You can simplify your code by eliminating unnecessary assignments to variables. The advantage of this function is that it can reduce bugs.

Count the number of repetitions with for statement etc., or as a value Because it is a useful function to use This is a useful function when writing iterative processing.

zip function

I'm sorry if it doesn't appear

The zip function uses two list types and is used in repetitions, etc. A function that allows you to use them at the same time.

zip (object, object)

First, prepare two list type variables We will use this in the for statement.


a = [1,2,3,4,5]
b = [6,7,8,9,0]

for i , j in zip(a,b):
    print(i,j)

1 6 2 7 3 8 4 9 5 0

The variables ʻiandj` have the values of the original list type variables, respectively. It will be stored.

If you try to use two lists without using the zip function It will look like this.

a = [1,2,3,4,5]
b = [6,7,8,9,0]

count=0
for i in a:
    print(i , b[count])
    count+=1

1 6 2 7 3 8 4 9 5 0

Of course it can be a source of bugs If it can be summarized as a process It's easier and cleaner code to use the zip function.

Also, for list type data that can be used with the zip function Must have the same number of elements.

sort

I'm sorry if it doesn't appear

Sort sorts the data. This is a process that is used quite often in programs.

** String type sorting (reverse order) **

You can use the index to turn the string upside down.

String [:: -1]

a1 = 'abcde Aiueo 123 Secretary!'
# [::-1]Turn it upside down
print(a1[::-1])

! Secretary 321 Oevia edcba

To sort the characters used in a string By converting to list type, sorting, and returning to string You can sort the character strings.

Use the sorted function to split and sort strings. Descending if you specify True for reverse of the second argument If False is specified or there is no second argument, the order is ascending.

a2 = 'abcde Aiueo 123 Secretary!'
#Convert to a list with the sorted function and sort in ascending order
print(sorted(a2,reverse=False))

#Convert to a list with the sorted function and sort in descending order
print(sorted(a2,reverse=True))

['!', '1', '2', '3','a','b','c','d','e','a','i','u',' D','o','thing','trunk'] ['Stem','Thing','O','E','U','I','A','e','d','c','b','a',' 3', '2', '1','!']

Use the join function to join list types one by one It can be a string.

'Join string'.join (list type)

a3 = 'abcde Aiueo 123 Secretary!'
print(''.join(sorted(a3 , reverse=True)))

Secretary Oevia edcba321!

Sorting only by character strings You may not have a chance to use it, but it is a useful technique in case of emergency.

** List type sort **

How to use the sort function, which is a list type function There is a method using the sorted function.

*** sort function ***

Ascending order: variable name.sort () Descending: variable name.sort (reverse = True)

*** sorted function ***

Ascending order: sorted (variable name) Descending: sorted (variable name, reverse = True)

Both are similar The sort function sorts the list and changes the sort order of the list type. The sorted function does a temporary sort, so it does not affect the sort order of the original list.

lis1= [3,1,2,4,5,7,6]
print(lis1)

#Ascending sort
print(sorted(lis1))

#The order does not change even if you call it again after the sorted function
print(lis1)

[3, 1, 2, 4, 5, 7, 6] [1, 2, 3, 4, 5, 6, 7] [3, 1, 2, 4, 5, 7, 6]

lis2= [3,1,2,4,5,7,6]
print(lis2)

#Sort in descending order
lis2.sort(reverse=True)
#If you call it after the sort function, the order will change.
print(lis2)

[3, 1, 2, 4, 5, 7, 6] [7, 6, 5, 4, 3, 2, 1]

Be careful if the order has a significant impact on your program.

Whether to keep the original shape or sort it before using it Consider how to process it and use it properly.

** Dictionary type sorting **

Dictionary type sorting Key ascending order andkey descending order Ascending order by value and descending order by value There are four ways.

Key ascending order: sorted (dictionary type variable .items ()) Ascending order of values: sorted (dictionary type variable .items (), key = lambda x: x [1]) Descending key: sorted (dictionary variable .items (), reverse = True) Descending order of values: sorted (dictionary variable .items (), key = lambda x: x [1], reverse = True)

#Key ascending order
dct = { 2:3, 3:4, 1:2, 0:8, 4:2 }
for k, v in sorted(dct.items()):
    print(k,':',v)

0 : 8 1 : 2 2 : 3 3 : 4 4 : 2

#Key descending order
dct = { 2:3, 3:4, 1:2, 0:8, 4:2 }
for k, v in sorted(dct.items(), reverse=True):
    print(k,':',v)

4 : 2 3 : 4 2 : 3 1 : 2 0 : 8

#Value ascending order
dct = { 2:'3', 3:'4', 1:'2', 0:'8', 4:'2' }
for k, v in sorted(dct.items(), key=lambda x:x[1]):
    print(k,':',v)

1 : 2 4 : 2 2 : 3 3 : 4 0 : 8

#Value descending order
dct = { 2:'3', 3:'4', 1:'2', 0:'8', 4:'2' }
for k, v in sorted(dct.items(), key=lambda x:x[1],reverse=True):
    print(k,':',v)

0 : 8 3 : 4 2 : 3 1 : 2 4 : 2

lambda is read as lambda, In python it is a reserved word for a anonymous function.

I'll talk more about lambda in a later lecture, so I will omit it here, but to sort by dictionary value, You have to write this way.

Since the dictionary type itself is a data type whose order does not have a big meaning It is common to sort only when using it.

For example, finally output only the top 1 In such a case, sort in descending order and output.

dct = { 2:'3', 3:'4', 1:'2', 0:'8', 4:'2' }

#First sort the dictionary in descending order of values and then incorporate it into the enumrate function
for i , d  in enumerate(sorted(dct.items(), key=lambda x:x[1],reverse=True)):
    if i>=1:
        #Exit the process the second time
        break
    print(i,d[0],d[1])

0 0 8

When iterating, first sort the dictionary in descending order of values. Look at the count returned by the ʻenumerate` function and exit the iterative process.

By doing so, when there is a large amount of data, it is possible to output up to the top number You will also be able to do that.

As a caveat, if you use the ʻenumerate function and the dictionary type ʻitems Please note that the returned data types are numeric type and tuple type.

In python, by using the sorted function, You can sort data in various forms.

I think it will help you to create a program that deals with things where alignment is important.

Comprehension notation

I'm sorry if it doesn't appear

The comprehension is a python-specific writing style It is a method for simply writing certain processes.

** How to write comprehension **

List: [value for variable in iterable object] Dictionary: {Key: Value for Variable in Iterable Object} Set: {value for variable in iterable object}

** Make a list using comprehensions **

[Value for variable in iterable object]

#Store list type in variable in inclusion notation
lis1 = [i for i in range(10)]
print(lis1)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you do not use comprehension

lis2 = []
for i in range(10):
    lis2.append(i)
print(lis2)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Inclusive notation can combine processing that spans multiple lines into one line.

** Create a dictionary using comprehensions **

{Key: Value for Variable in Iterable Object}

#Enumerate the key in a comprehension,Create dictionary type as a result of range value
num_dict = {k:v for k,v in enumerate(range(2,30,3))}
print(num_dict)

{0: 2, 1: 5, 2: 8, 3: 11, 4: 14, 5: 17, 6: 20, 7: 23, 8: 26, 9: 29}

You can create a dictionary type if there is a corresponding key and value. You can also use the ʻIF statement` in the comprehension.

** Included notation + IF statement **

List: [value for variable in iterable object if condition] Dictionary: {key: value if condition for variable in iterable object}

** Included notation + IF, else statement **

List: [value 1 if condition else value 2 for variable in iterable object] Dictionary: {key 1 if conditional else key 2: value 1 if conditional else value 2 for variable in iterable object}

#List comprehension+IF statement
num_list = [i for i in range(15) if i%2==0]
print(num_list)

[0, 2, 4, 6, 8, 10, 12, 14]

#List comprehension+ IF ,else statement
num_list = [i if i%2==0 else 0 for i in range(15) ]
print(num_list)

[0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10, 0, 12, 0, 14]

#Dictionary comprehension+IF statement
num_dict = {k:v for k,v in enumerate(range(2,30,3)) if k%2==0}
print(num_dict)

{0: 2, 8: 26, 2: 8, 4: 14, 6: 20}

#Dictionary comprehension+ IF ,else statement
num_dict = {k if k%2==0 else 0 : v if k%2==0 else 0  
for k,v in enumerate(range(2,30,3)) }
print(num_dict)

{0: 0, 8: 26, 2: 8, 4: 14, 6: 20}

The dictionary type is the zip function without using the ʻenumerate` function. You can also make it using two lists.

lis_a = [1,2,3,4,5]
lis_b = ['a','b','c','d','e']
d2 = {k:v for k,v in zip(lis_a,lis_b)}
print(d2)

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

You can also create a dictionary from the list comprehension IFELSE statement.

#From list comprehension to dictionary
num_dict = dict((str(i),i) if i%2==0 else (i,str(i)) for i in range(10))
print(num_dict)

{9: '9', 1: '1', 3: '3', '8': 8, 5: '5', '0': 0, '2': 2, '4': 4, '6': 6, 7: '7'}

You can write multiple for statements in the comprehension notation.

[Value for Variable 1 in Iterable Object for Variable 2 in Iterable Object]

#Double inclusion notation
print([i*j for i in range(1,5) for j in range(1,4) ])

[1, 2, 3, 2, 4, 6, 3, 6, 9, 4, 8, 12]

Let's write this in a normal for statement.

a5 = []
for i in range(1,5):
    for j in range(1,4):
        a5.append(i * j)
print(a5)

[1, 2, 3, 2, 4, 6, 3, 6, 9, 4, 8, 12]

The one written later corresponds to the inner for statement.

It is possible to write things that span multiple lines in one line. It is a good point of the inclusion notation.

Start by writing the normal process correctly, If there is a part that can simplify it, change it to a comprehension notation If you do something like this, you will be able to remember it well.

Summary

Python has many functions as standard functions Do the same without writing a lot of useless code It can be done with a small amount of code.

By combining functions You can also reduce the amount of code It's helpful to remember the behavior of commonly used functions.

Because sorting is always done when sorting data How to rearrange and how to write code Let's hold it down.

Included notation is a Python-specific notation You can write a process that spans multiple lines in one line This will lead to a reduction in the amount of code and execution time.

A small amount of code suppresses the occurrence of bugs It also shortens the debugging time. Let's learn how to write Python-specific.

70 days until you become an engineer

Author information

Otsu py's HP: http://www.otupy.net/

Youtube: https://www.youtube.com/channel/UCaT7xpeq8n1G_HcJKKSOXMw

Twitter: https://twitter.com/otupython

Recommended Posts

You will be an engineer in 100 days ――Day 24 ―― Python ―― Basics of Python language 1
You will be an engineer in 100 days ――Day 30 ―― Python ―― Basics of Python language 6
You will be an engineer in 100 days ――Day 25 ―― Python ―― Basics of Python language 2
You will be an engineer in 100 days --Day 29 --Python --Basics of the Python language 5
You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8
You will be an engineer in 100 days --Day 26 --Python --Basics of the Python language 3
You will be an engineer in 100 days --Day 32 --Python --Basics of the Python language 7
You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4
You will be an engineer in 100 days --Day 27 --Python --Python Exercise 1
You will be an engineer in 100 days --Day 34 --Python --Python Exercise 3
You will be an engineer in 100 days --Day 31 --Python --Python Exercise 2
You will be an engineer in 100 days --Day 63 --Programming --Probability 1
You will be an engineer in 100 days --Day 65 --Programming --Probability 3
You will be an engineer in 100 days --Day 64 --Programming --Probability 2
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
You will be an engineer in 100 days --Day 86 --Database --About Hadoop
You will be an engineer in 100 days ――Day 71 ――Programming ――About scraping 2
You will be an engineer in 100 days ――Day 61 ――Programming ――About exploration
You will be an engineer in 100 days ――Day 74 ――Programming ――About scraping 5
You will be an engineer in 100 days ――Day 73 ――Programming ――About scraping 4
You will be an engineer in 100 days ――Day 75 ――Programming ――About scraping 6
You will be an engineer in 100 days --Day 68 --Programming --About TF-IDF
You will be an engineer in 100 days ――Day 70 ――Programming ――About scraping
You will be an engineer in 100 days ――Day 81 ――Programming ――About machine learning 6
You will be an engineer in 100 days ――Day 82 ――Programming ――About machine learning 7
You will be an engineer in 100 days ――Day 79 ――Programming ――About machine learning 4
You will be an engineer in 100 days ――Day 76 ――Programming ――About machine learning
You will be an engineer in 100 days ――Day 80 ――Programming ――About machine learning 5
You will be an engineer in 100 days ――Day 78 ――Programming ――About machine learning 3
You will be an engineer in 100 days ――Day 83 ――Programming ――About machine learning 8
You will be an engineer in 100 days ――Day 77 ――Programming ――About machine learning 2
You will be an engineer in 100 days ――Day 85 ――Programming ――About machine learning 10
You will be an engineer in 100 days ――Day 60 ――Programming ――About data structure and sorting algorithm
You become an engineer in 100 days ――Day 66 ――Programming ――About natural language processing
You become an engineer in 100 days ――Day 67 ――Programming ――About morphological analysis
Become an AI engineer soon! Comprehensive learning of Python / AI / machine learning / deep learning / statistical analysis in a few days!
Basics of Python ①
Basics of python ①
Python: Deep Learning in Natural Language Processing: Basics
Basics of I / O screen using tkinter in python3
Japan may be Galapagos in terms of programming language
How to use Python Kivy ① ~ Basics of Kv Language ~
When you get an error in python scraping (requests)
How much do you know the basics of Python?
Basics of Python scraping basics
# 4 [python] Basics of functions
Basics of python: Output
If you draw an Omikuji with a probability of 1% 100 times in a row, will you win once?
Processing of python3 that seems to be usable in paiza
A liberal arts engineer tried knocking 100 language processes in Python 02
What beginners learned from the basics of variables in python
A liberal arts engineer tried knocking 100 language processes in Python 01
A liberal arts engineer tried knocking 100 language processes in Python 00
Quicksort an array in Python 3
Resolve the Address already in use error
Date of Address already in use error in Flask
Error in Flask OSError: [Errno 98] Address already in use
· Address already in use solution
If you get Error: That port is already in use. In Django
You will be an engineer in 100 days --Day 29 --Python --Basics of the Python language 5
You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8
You will be an engineer in 100 days --Day 26 --Python --Basics of the Python language 3
You will be an engineer in 100 days --Day 32 --Python --Basics of the Python language 7
You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4
You have to be careful about the commands you use every day in the production environment.
When you get an error in python scraping (requests)
Solution if the module is installed in Python but you get an error in Jupyter notebook
Python is an adult language
Equivalence of objects in Python
python: Basics of using scikit-learn ①
Implementation of quicksort in Python
Basics of Python × GIS (Part 1)
Will the day come when Python can have an except expression?