Python data structure and operation (Python learning memo ③)

This time is a learning memo about the data structure of objects handled by Python

Methods that can be used in lists

Add element

list.append(x) Add an item to the end of the list Equivalent to a [list (a):] = [x]

list.extend(L) Extend the list by adding all the items in the given list L to the end of the list Equivalent to a [len (a):] = L

list.insert(i, x) Inserts an item at the specified position. The first argument is the element index. The insertion is done before this element. a.insert (0, x) will insert it at the beginning of the list a.insert (len (a), x) is equivalent to a.append (x)

Delete and retrieve elements

list.remove(x) Delete the first item with the value x Error if it does not exist

list.pop([i]) Removes the item at the specified position from the list and returns this item Returns the last item if no index is specified and removes it from the list

list.clear() Remove all items from the list Equivalent to del a [:]

Other operations

list.index() Returns the index of the first item with a value of x. Error if no such item exists

list.count(x) Returns the number of x in the list

list.sort(key=None, reverse=False) Sort list objects directly (make changes directly without making a copy of the list) Sorting can be customized with arguments

list.reverse() Directly reverse the list object

list.copy() Returns a shallow copy of the list Equivalent to a [:]

a = [66.25, 333, 333, 1, 1234.5]

print(a.count(333), a.count(66.25), a.count('x'))
# 2 1 0

a.insert(2, -1)
a.append(333)
print(a)
# [66.25, 333, -1, 333, 1, 1234.5, 333]

print(a.index(333))
# 1

a.remove(333)
print(a)
# [66.25, -1, 333, 1, 1234.5, 333]

a.reverse()
print(a)
# [333, 1234.5, 1, 333, -1, 66.25]

a.sort()
print(a)
# [-1, 1, 66.25, 333, 333, 1234.5]

print(a.pop())
# 1234.5

print(a)
# [-1, 1, 66.25, 333, 333]

Use the list as a stack

point

Last-in first-out example


stack = [3, 4, 5]

stack.append(6)
stack.append(7)

print(stack)
# [3, 4, 5, 6, 7]

print(stack.pop())
# 7

print(stack)
# [3, 4, 5, 6]

print(stack.pop())
# 6

Use the list as a queue

point

collection.Queue with deque(First in first out)Implementation of


from collections import deque

queue = deque(["Bill", "Earl", "Sam"])
queue.append("Andy")
queue.append("Chris")
print(queue.popleft())
# Bill
print(queue.popleft())
# Earl
print(queue)
# deque(['Sam', 'Andy', 'Chris'])

List comprehension

point

A simple example of generating a list of squares


#Generate a list of squares
squares = []
for x in range(10):
    squares.append(x**2)
    
print(squares)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 

#The above process leaves a variable called x
print(x)

#You can create a list without side effects by doing the following
squares = list(map(lambda x: x**2, range(10)))

#If you write ↑ in a list comprehension, it will be as follows
squares = [x**2 for x in range(10)]

A little more complicated example


combs = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
print(combs)
# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

#This is equivalent to
combs = []
for x in [1, 2, 3]:
    for y in [3, 1, 4]:
        if x != y:
            combs.append((x, y))

print(combs)
# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Other convenient usage


vec = [-4, -2, 0, 2, 4]
#Generate a new list with doubled values
double = [x*2 for x in vec]

print(double)
# [-8, -4, 0, 4, 8]

#Filter to remove negative numbers
positive_list = [x for x in vec if x >= 0]
print(positive_list)
# [0, 2, 4]

Nested list comprehension

point

Swap rows and columns in an array


matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

#Swap rows and columns
reversed_matrix = [[row[i] for row in matrix] for i in range(4)]
print(reversed_matrix)
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Example of zip function


matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]

print(list(zip(*matrix)))
# [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

del statement

point

Example of using the del statement


a = [-1, 1, 66.25, 333, 333, 1234.5]

#Specified by index
del a[0]

print(a)
# [1, 66.25, 333, 333, 1234.5]

#Specified by slice
del a[2:4]

print(a)
# [1, 66.25, 1234.5]

#Clear the entire list
del a[:]

print(a)
# []

#Delete the entire variable (after that, referencing a will result in an error)
del a

Tuples and sequences

point

Tuple operation


#Tuples consist of comma-separated values (tuple packing)
t = 12345, 54321, 'hello!'

#Unpacking is also possible by the following method(Sequence unpacking)
x, y, z = t
print(x) # 12345
print(y) # 54321
print(z) # hello!

print(t)
# (12345, 54321, 'hello!')

#Tuples can be nested
u = t, (1, 2, 3, 4, 5)

print(u)
# ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

#Tuples cannot be changed
# t[0] = 88888

#Modifiable objects can be stored
v = ([1, 2, 3], [3, 2, 1])
print(v)
# ([1, 2, 3], [3, 2, 1])

#Empty tuple
empty = ()

#Tuple with 1 element
singleton = 'hello', <-Add a comma at the end

Set

point

set example


basket = {'apple', 'orage', 'apple', 'pear', 'orange', 'banana'}
print(basket)
# {'banana', 'pear', 'apple', 'orage', 'orange'}

print('orange' in basket) #High-speed existence judgment
# True
print('crabgrass' in basket)
# False

#Set operation by taking unique letters from two words
a = set('abracadabra')
b = set('alacazam')

#unique character of a
print(a)
# {'r', 'a', 'c', 'b', 'd'}

#Characters that exist in a but not in b
print(a - b)
{'r', 'b', 'd'}

#Characters present in a or b
print(a | b)
# {'z', 'r', 'a', 'c', 'b', 'd', 'l', 'm'}

#Characters that exist in both a and b
print(a & b)
# {'c', 'a'}

#Uncommon characters in a or b
print(a ^ b)
# {'m', 'b', 'l', 'z', 'd', 'r'}

#Set comprehensions that are very similar to list comprehensions are also supported
a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)
# {'r', 'd'}

dictionary

point

Dictionary type example


#Initialization
tel = {'jack': 4098, 'sape': 4139}

#add to
tel['guido'] = 4127
print(tel) # {'jack': 4098, 'sape': 4139, 'guido': 4127}
print(tel['jack']) # 4098

#Delete
del tel['sape']
tel['irv'] = 4127
print(tel)
# {'jack': 4098, 'guido': 4127, 'irv': 4127}

#Get a list of keys
print(list(tel.keys()))
# ['jack', 'guido', 'irv']

#Sort by key
print(sorted(tel.keys()))
# ['guido', 'irv', 'jack']

#Existence check
print('guido' in tel) # True
print('jack' not in tel) # False

# dict()The constructor is the key:From a sequence of tuples of value pairs
#Build a dictionary
tel2 = dict([('sape', 4139), ('guide', 4127), ('jack', 4098)])
print(tel2)
# {'sape': 4139, 'guide': 4127, 'jack': 4098}

#Dictionary comprehensions can be used to generate dictionaries from arbitrary expressions that give keys and values
print({x: x**2 for x in (2, 4, 6)})
# {2: 4, 4: 16, 6: 36}

#If the key is a string, it may be easier to specify the pair with keyword arguments
tel3 = dict(sape=4139, guido=4127, jack=4098)
print(tel3)
# {'sape': 4139, 'guido': 4127, 'jack': 4098}

Loop technique

point

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
    print(k, v)

# gallahad the pure
# robin the brave
for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)

# 0 tic
# 1 tac
# 2 toe
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']

for q, a in zip(questions, answers):
    print('What is your {0}? It is {1}.'.format(q, a))
    
# What is your name? It is lancelot.
# What is your quest? It is the holy grail.
# What is your favorite color? It is blue.
for i in reversed(range(1, 10, 2)):
    print(i)
    
# 9
# 7
# 5
# 3
# 1
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

for f in sorted(set(basket)):
    print(f)
    
# apple
# banana
# orange
# pear


import math

raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
    if not math.isnan(value):
        filtered_data.append(value)
        
print(filtered_data)
# [56.2, 51.7, 55.3, 52.5, 47.8]

About the conditions used for comparing objects

point

string1, string2, string3 = '', 'Tronbheim', 'Hammer Dance'
non_null = string1 or string2 or string3
print(non_null)
# Tronbheim

Sequence comparison, other type comparison

point

Object comparison


(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)

Recommended Posts

Python data structure and operation (Python learning memo ③)
Python data structure and internal implementation ~ List ~
Python class (Python learning memo ⑦)
Python module (Python learning memo ④)
[Python tutorial] Data structure
Python decorator operation memo
[Python] Conversion memo between time data and numerical data
data structure python push pop
Python learning memo for machine learning by Chainer Chapters 1 and 2
Python and ruby slice memo
Python data analysis learning notes
Python data type summary memo
Solve the spiral book (algorithm and data structure) with python!
Python control syntax, functions (Python learning memo ②)
Difference between java and python (memo)
[Python] Operation memo of pandas DataFrame
Memo "Chapter 5 – Dictionaries and Structuring Data"
[python] week1-3: Number type and operation
Hashing data in R and Python
Python memo ① Folder and file operations
Picture book data structure algorithm Python
Interval scheduling learning memo ~ by python ~
"Scraping & machine learning with Python" Learning memo
Python memo
python memo
Python memo
python memo
python learning
Python memo
Python memo
Python memo
Data pipeline construction with Python and Luigi
Statistical basics and Python, graphing, etc. (memo)
Python numbers, strings, list types (Python learning memo ①)
[Python beginner memo] Python character string, path operation
Python: Preprocessing in machine learning: Data acquisition
Python basic operation 3rd: Object-oriented and class
[Python] First data analysis / machine learning (Kaggle)
Easily graph data in shell and Python
Python and machine learning environment construction (macOS)
Data analysis starting with python (data preprocessing-machine learning)
Python standard library: second half (Python learning memo ⑨)
Python: Preprocessing in machine learning: Data conversion
Compress python data and write to sqlite
Python & Machine Learning Study Memo ③: Neural Network
Python & Machine Learning Study Memo ④: Machine Learning by Backpropagation
Python & Machine Learning Study Memo ⑥: Number Recognition
Exchange encrypted data between Python and C #
Python standard library: First half (Python learning memo ⑧)
Memo of pixel position operation for image data in Python (numpy, cv2)
Quickly build a python environment for deep learning and data science (Windows)
Make a decision tree from 0 with Python and understand it (4. Data structure)
Python: Preprocessing in machine learning: Handling of missing, outlier, and imbalanced data
[Python] Memo dictionary
LPIC201 learning memo
Correspondence summary of array operation of ruby and python
[Python] Learning Note 1
python beginner memo (9.2-10)
Python learning notes
[python] vector operation
Python variables and data types learned in chemoinformatics