Understand python lists, dictionaries, and so on.

list

list()

Generate / convert a list. Character string → list and tuple → list are possible.

Generate


hoge = []
hoge = list()  #Same as above

conversion


list('cat')
# ['c','a','t']

Offset

slice


hoge = ['a','b','c','d']
hoge[::2]
# ['a','c']
hoge[::-2]
# ['d','b'] #From the opposite
hoge[::-1]
# ['d','c','b','a'] #In reverse order

append() extend()

Add and combine


hoge = ['a','b','c','d']
fuga = ['e']

hoge.append('e')
hoge.extend(fuga)
hoge += fuga
# ['a','b','c','d','e'] #All the same result

insert()

piyo = ['a','b','d','e']
piyo.insert(2, 'c')
# ['a','b','c','d','e']

remove() pop()

hoge = ['a','b','c','d','e']
hoge.remove('d') #Delete by specifying the element itself
hoge.pop(3) #Delete by specifying an offset(To be exact, take out)
# hoge = ['a','b','c','e'] #Same result

Existence check

hoge = ['a','b','c','d','e']
if 'a' in hoge:
    print("exist")
else
    print("not exist")
# exist

split() join()

fuga = 'a,b,c,d'
fuga.split(',')
# ['a','b','c','d']

hoge = ['a','b','c','d']
','.join(hoge)    #hoge.join(',')Note that it is not!
# 'a,b,c,d'

copy()

Python is basically passed by reference.

hoge = ['a','b','c','d']
fuga = hoge
#If you change hoge after this, fuga will also reflect the change.=fuga refers to hoge.

fuga = hoge.copy()
fuga = list(hoge)
fuga = hoge[:]
#Any of these generate a copy rather than a reference, so fuga keeps the original list even if you change the hofge.

Get offset and value enumerate ()

hoge = ['a','b','c','d']
for i, val in enumerate(hoge):
    print(i, val)

Tuple

The difference from the list is that it is immutable, that is, the changes do not work.

Create


hoge = 4, 10, 5
hoge = (4, 10, 5)
hoge = tuple(4, 10, 5)  #All the same.

Unpack

The contents of tuples can be assigned to each variable without using temporary variables.

Unpack


hoge = tuple(4, 10, 5)
a, b, c = hoge

dictionary

dict()

Generate


hoge = {}
hoge = dict()

conversion


fuga = [('a', 'b'), ('c', 'd')] #Lists of lists can also be converted
hoge = dict(fuga)
# {
#     'a': 'b',
#     'c': 'd'
# }

piyo = list(hoge.items()) #Converted with a list of tuples.(In addition, list()If you don't bite the dict_Returns in the form of items.)
# [('a', 'b'), ('c', 'd')]

#The reason for applying as follows is because it uses the unpacked nature of tuples.
for key, item in hoge.items():
    pass

Add and combine


hoge = {
    'a': 'b',
    'c': 'd'
}
hoge['e'] = 'f' #You can specify it without permission

fuga = {
    'g': 'h'
}
hoge.update(fuga) #Join

Existence check

Same as the list.

hoge = {
    'a': 'b',
    'c': 'd'
}
if 'a' in hoge:
    print("exist")
else
    print("not exist")
# exist

keys() values()

hoge = {
    'a': 'b',
    'c': 'd'
}
hoge.keys()
# dict_keys(['a', 'c'])→ Returns an iterable key view. list()Need to bite and convert to a list.
list(hoge.keys())
# ['a', 'c']

values () is the same as above.

copy()

Same as the list. When not passing by reference.

set

When you don't care about the order. The shape is represented as {0, 2, 7, 1, 4}.

Create


hoge = set()           #Empty set
hoge = {0, 2, 7, 1, 4} #A set that also defines the contents
hoge = {}              #This is a dictionary

hoge = set( ["hoge", "fuga", "piyo"] ) #In addition to lists, tuples, character strings, and dictionaries are also supported.(Only key is extracted in the dictionary)
# {"piyo", "hoge", "fuga"}

Byte sequence

bytes → Something like a tuple of bytes, immutable. bytearray → Something like a list of bytes, mutable.

Other functions

zip()

Return the tuple. It can be used as follows by unpacking with a for statement.

hoge = ["a", "b", "c"]
fuga = ["A", "B", "C", "D"]

for small, large in zip(hoge, fuga):
    print("small:", small, "large:", large)

# small: a large: A
# small: b large: B
# small: c large: C  #Finish according to the shorter one,"D"It doesn't come out.

range()

Creating a sequence. The syntax range (start, end, step). Up to the number just before ʻend`.

range(0, 3)
# 0, 1, 2

Comprehension notation

List comprehension

Write a for loop without the [] in the list.

Syntax 1


 [Expression for variable in iterable object]

Example


hoge = [num for num in range(0, 3)]
# [0, 1, 2]

fuga = [num * 2 for num in range(0, 3)]
# [0, 2, 4]

piyo = [(a, b) for a in range(0, 2) for b in range(0, 3)]
#[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

Syntax 2


 [Expression for variable in iterable object if condition]

Example


hoge = [num for num in range(0, 3) if num % 2 == 0]
# [0, 2]

Dictionary comprehension

syntax


 {formula:formulafor 変数 in イテラブルオブジェクト }

Example


word = "letter" #It's ok to keep a list or set
hoge = { let : word.count(let) fot let in word }
# { "l": 1, "e": 2, "t": 2, "r": 1}

Set comprehension

the same. abridgement

× Tuple comprehension ○ Generator type

→ There is no inclusion notation in tuples! Writing in the same format as above returns a generator object.

Recommended Posts

Understand python lists, dictionaries, and so on.
Python3 | Lists, Tuples, Dictionaries
Python lists, tuples, dictionaries
[Short sentence] [Python] Format and print lists and dictionaries
Understand Python packages and modules
Save lists, dictionaries and tuples to external files python
Notes on Python and dictionary types
[Python / matplotlib] Understand and use FuncAnimation
Find memory-consuming lists / arrays on Python
Integrate Modelica and Python on Windows
Python and Bash on Cisco Catalyst IOS-XE
Build Python3 and OpenCV environment on Ubuntu 18.04
A memo with Python2.7 and Python3 on CentOS
Notes on building Python and pyenv on Mac
See file and folder information on python
Install pyenv and Python 3.6.8 on Ubuntu 18.04 LTS
Try to write python code to generate go code --Try porting JSON-to-Go and so on
How to use lists, tuples, dictionaries, and sets
Install and run Python3.5 + NumPy + SciPy on Windows 10
Python on Windows
(Windows) Causes and workarounds for UnicodeEncodeError on Python 3
twitter on python3
Install OpenCV 4.0 and Python 3.7 on Windows 10 with Anaconda
PHP and Python integration from scratch on Laravel
Python on Windbg
[Note] Installing Python 3.6 + α on Windows and RHEL
Try importing MLB data on Mac and Python
Install MongoDB on Ubuntu 16.04 and operate via python
Install Python and libraries for Python on MacOS Catalina
Install ZIP version Python and pip on Windows 10
Initial settings for using Python3.8 and pip on CentOS8
Notes on HDR and RAW image processing with Python
Visualize and understand Japan's regional mesh on a map
Install selenium on Mac and try it with python
Carefully understand the exponential distribution and draw in Python
Plot and understand the multivariate normal distribution in Python
Automatic follow on Twitter with python and selenium! (RPA)
Show progress bar and remaining time on console (python)
Get comments on youtube Live with [python] and [pytchat]!
Carefully understand the Poisson distribution and draw in Python
[Windows] [Python3] Install python3 and Jupyter Notebook (formerly ipython notebook) on Windows
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Compile and install MySQL-python for python2.7 on amazon linux
Email hipchat with postfix, fluentd and python on Azure
Automate Chrome with Python and Selenium on your Chromebook
Create a decent shell and python environment on Windows
[Python] Extract only numbers from lists and character strings
Install django on python + anaconda and start the server
Set up python and machine learning libraries on Ubuntu
[python] Compress and decompress
Install python on WSL
Python and numpy tips
[Python] pip and wheel
PyOpenGL setup on Python 3
Install Python on Pidora.
Batch design and python
Python iterators and generators
Install Mecab and CaboCha on ubuntu16.04LTS so that it can be used from python3 series
Python packages and modules
Vue-Cli and Python integration
Memorize Python commentary 5 --Lists