This is the only basic review of Python ~ 2 ~

Continuation from the above This is the only basic review of Python ~ 1 ~

4. List []

How to use the list

--How to output list values.

Index counts from 0

spam = ['cat', 'bat', 'rat', 'elephant']
spam = [0]
cat
spam = [1]
bat
spam = [2]
rat
spam = [3]
elephant

--Negative index

spam = ['cat', 'bat', 'rat', 'elephant']
spam = [-1]
elephant

--How to output the value of the list in the list.

The first [] specifies the list, and the second [] specifies the value.

spam = [['cat', 'bat', 'rat', 'elephant'], ['1', '2', '3']]
spam = [0][1]
bat

--How to output a partial list

A partial list can be obtained by using slices. __ The first argument represents the start index and the second argument represents the value one less than the end value. __ If the __ value is omitted, it will be 0. __

spam = ['cat', 'bat', 'rat', 'elephant']
spam = [0:3]
['cat', 'bat', 'rat']
spam = [:2]
 ['cat', 'bat']

--Change the value of the list using the index

spam = ['cat', 'bat', 'rat', 'elephant']
spam[4] = 12345
spam
['cat', 'bat', 'rat', 12345]

--Remove the value from the list using the del statement.

spam = ['cat', 'bat', 'rat', 'elephant']
del spam[2]
spam
['cat', 'bat', 'elephant']

--Multiple substitution method

When assigning a list value to a variable, it can be written shorter than the following program.

spam = ['cat', 'bat', 'rat', 'elephant']
size = spam[0]
color = spam[1]
cat = spam[2]

print(size)
cat
print(color)
bat
print(cat)
rat
#The following is the multiple substitution method
spam = ['cat', 'bat', 'rat', 'elephant']
size, color, cat = spam

--for loops and lists

The following program assigns the list of cats_name to name in order.

for name in cats_name:
    print(name)
#This is the same behavior as the program below
for i in range(1, 6)
    print(i)

--List exception

Lists are an exception to the indentation rule You can use the concatenated character \ (backslash) to start a new line or indent.

Method

--index () method

Output the index from the values in the list.

spam = ['cat', 'bat', 'rat', 'elephant']
spam.index('bat')
1

--append () method __ (list method) __

Add a new value to the list.

spam = ['cat', 'bat', 'rat', 'elephant']
spam.append('moose')
spam
['cat', 'bat', 'rat', 'elephant', 'moose']

--insert () method __ (list method) __

Unlike the append () method, append a value anywhere. Enter the index in the first argument and the value in the second argument.

spam = ['cat', 'bat', 'rat', 'elephant']
spam.insert(1, 'chicken')
spam
['cat', 'chicken', 'bat', 'rat', 'elephant']

--remove () method

Remove the value from the list. When the __remove () method knows the value you want to remove. __ The __del statement is when you know the index of the value you want to delete. __ __ If there are multiple values, only the first value is deleted. __

spam = ['cat', 'bat', 'cat', 'rat', 'elephant']
spam.remove('cat')
spam
['bat', 'cat', 'rat', 'elephant']

--sort () method

Sort the values in the list.

spam = [2, 5, 3.14, 1, -7]
spam.sort()
spam
[-7, 1, 2, 3.14, 5]

If you want to sort in reverse order, specify True for reverse of the keyword argument.

spam = [2, 5, 3.14, 1, -7]
spam.sort(reverse=True)
spam
[5, 3.14, 2, 1, -7]

Because the sort () method sorts in alphabetical order If you want to sort alphabetically, pass str.lower to the keyword argument key.

spam = ['a', 'z', 'A', 'Z']
spam.sort(key=str.lower)
spam
['a', 'A', 'z', 'Z']

Strings and lists

Character strings can be treated as a list.

name = 'Zophie'
name[0]
'Z'
name[-2]
'i'
name[:4]
'Zoph'

for i in name:
    print(i)
'Z'
'o'
'p'
'h'
'i'
'e'

Mutable, immutable

The list is mutable (changeable) Strings are immutable (cannot be changed)

Tuple type

There are two differences from the list [].

-Use () instead of []. --Immutable.

__ When the tuple has one element, add a comma like ('Hello',). __

list () function, tuple () function

--Tuple the list.

tuple(['cat', 'dog', 5])
('cat', 'dog', 5)

--List tuples.

list('Hello')
['H', 'e', 'l', 'l', 'o']

copy module and copy (), deepcopy ()

Used when duplicating lists and dictionaries.

--copu.copy () Duplicate list and dictionary --copy.deepcopy Duplicate the list or dictionary in the list or dictionary

import copy
spam = ['A', 'B', 'C', 'D']
cheese = copy.copy(spam)
cheese[1] = 42
spam
['A', 'B', 'C', 'D']
cheese
['A', 42, 'C', 'D']

5. Dictionary and data structure

Dictionary type

Whereas the list index was an integer type Dictionaries can use various data types. List [] Tuple () __Dictionary {} __ The index of the dictionary is called key, and the key and value are combined and called key-value pair.

--How to access the value

my_cat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
my_cat['size']
'fat'

Comparison of dictionary and list

Dictionaries, unlike lists, have no element order. That is, the index can start at any value. You can't use slices because there is no order.

A method that returns a list-like value

The following three methods return list-like values when used in a dictionary.

--keys () method

Returns the key of the dictionary.

spam = {'color': 'red', 'age': 42}
for k in spam.keys():
    print(k)
color
age

--values () method

Returns the __value __ of the dictionary.

spam = {'color': 'red', 'age': 42}
for v in spam.values():
    print(v)
red
42

--items () method

Returns the __key-value pair __ of the dictionary.

spam = {'color': 'red', 'age': 42}
for i in spam.items():
    print(i)
('color', 'red')
('age', 42)

--Application of items () method

Keys and values can be assigned to separate variables

spam = {'color': 'red', 'age': 42}
for k, v in spam.items():
    print('Key: ' + k +'Value: ' + str(v))
Key: color Value: red
Key: age Value: 42

get () method

The get () method can be set to return an arbitrary value when the key you want to access does not exist. In other words, it is possible to avoid the error that occurs when the key does not exist in the dictionary. __ Enter the key you want to access and the value to return if it doesn't exist. __

picnic_items = {'apples': 5, 'cups': 2}
print('I am bringing' + str(picnic_items.get('cups', 0)) + ' cups.'
I am bringing 2 cups.
#When the key does not exist, it becomes as follows.
picnic_items = {'apples': 5, 'cups': 2}
print('I am bringing' + str(picnic_items.get('eggs', 0)) + ' cups.'
I am bringing 0 cups.

setdefault () method

If the key is not registered in the dictionary, the key-value pair can be registered. Enter the key you want to check in the first argument and the value to be registered when the key does not exist in the second argument.

spam = {'name': 'Pooka', 'age': 5}
spam.setdefault('color', 'black')
spam
{'name': 'Pooka', 'age': 5, 'color': 'black'}
#If it exists, it will be as follows.
spam = {'name': 'Pooka', 'age': 5}
spam.setdefault('color', 'white')
spam
{'name': 'Pooka', 'age': 5, 'color': 'black'}

Formatted display

When you import the pprint module, you can use the pprint () and pformat () functions. These can display the contents of the dictionary neatly.

Display a formatted dictionary. When used in a program that counts the number of characters, it becomes as follows.

import pprint
message='It was a bright cold day in April, and the clocks were striking thirteen.'
count={}
for character in message:
    count.setdefault(character,0)
    count[character]=count[character]+1
pprint.pprint(count)
{' ': 13,
 ',': 1,
 '.': 1,
 'A': 1,
 'I': 1,
 'a': 4,
 'b': 1,
 'c': 3,
 'd': 3,
 'e': 5,
 'g': 2,
 'h': 3,
 'i': 6,
 'k': 2,
 'l': 3,
 'n': 4,
 'o': 2,
 'p': 1,
 'r': 5,
 's': 3,
 't': 6,
 'w': 2,
 'y': 1}

pprint.pprint () prints on the screen, while pprint.pformat () does not. So the following two sentences are equivalent. pprint.pprint(spam) print(pprint.pformat(spam))

Python basic review list

This is the only basic review of Python ~ 1 ~

Recommended Posts

This is the only basic review of Python ~ 2 ~
This is the only basic review of Python ~ 3 ~
Review of the basics of Python (FizzBuzz)
[python] [meta] Is the type of python a type?
Python Basic Course (at the end of 15)
The answer of "1/2" is different between python2 and 3
the zen of Python
Basic knowledge of Python
Summary of the basic flow of machine learning with Python
Impressions of taking the Python 3 Engineer Certification Basic Exam
Why is the first argument of [Python] Class self?
[Introduction to Python] Basic usage of the library matplotlib
Towards the retirement of Python2
Basic usage of Python f-string
About the features of Python
The Power of Pandas: Python
Python Basic Course (1 What is Python)
I wrote the basic grammar of Python with Jupyter Lab
What is the default TLS version of the python requests module?
Initial setting of Mac ~ Python (pyenv) installation is the fastest
[Python] The stumbling block of import
First Python 3 ~ The beginning of repetition ~
Is the probability of precipitation correct?
[Python] What is @? (About the decorator)
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
What kind of Kernel is this Kernel?
[python] What is the sorted key?
Change the Python version of Homebrew
About the basic type of Go
This and that of python properties
[Python] Understanding the potential_field_planning of Python Robotics
Basic grammar of Python3 system (dictionary)
What is the python underscore (_) for?
Science "Is Saito the representative of Saito?"
About the basics list of Python basics
Basic study of OpenCV with Python
Learn the basics of Python ① Beginners
[Python] Organize the basic structure of Flask apps (Aim for de-copying)
March 14th is Pi Day. The story of calculating pi with python
[Python] Display only the elements of the list side by side [Vertical, horizontal]
How to use the asterisk (*) in Python. Maybe this is all? ..
Try running the basic information Python sample problem only in the browser
A memorandum regarding the acquisition of the Python3 engineer certification basic exam
Change the length of Python csv strings
What is the XX file at the root of a popular Python project?
This and that of the inclusion notation.
[Linux] Review of frequently used basic commands 2
(Bad) practice of using this in Python
Pass the path of the imported python module
The story of making Python an exe
Learning notes from the beginning of Python 1
Check the existence of the file with python
About the virtual environment of python version 3.7
What kind of programming language is Python?
Review the concept and terminology of regression
What is the cause of the following error?
[Python] Understand the content of error messages
Where is the python instantiation process written?
[Python3] Rewrite the code object of the function
I didn't know the basics of Python