20241116-技能训练


Python学习笔记

和字符串相关的常用操作

字符串的定义

  • 双引号

    string_in_double_quotes = "Hello, Python!"
    
  • 单引号

    string_in_single_quotes = 'Hello, Python!'
    
  • 三引号(用于多行输入)

    string_in_triple_quotes = '''Hello, Python!
    I believe that ‘BOXUE’ will let me become stronger and stronger.
    However, only “hard work” makes me better than before.'''
    

当字符串本身需要引号时,就使用另外的引号形式将其包裹,防止歧义

  • 数字通过类型转换来定义

    number = 1145141919810
    number_to_string = str(number)
    

python中的字符串是只读的,不能根据存储位置进行修改

字符串的拼接

action = 'Hello'
name = 'Leo'
welcome = action + ", " +name

字符串全部大写/小写

welcome.upper()
welcome.lower()

字符串去掉首尾空格

welcome.strip()

查看字符串可用的方法

dir(welcome)
help(welcome.upper)

分割字符串

  • 可以像C一样,使用单个字符的位置读取内容

    welcome[0]
    
  • 也可以使用一个range,截取字符串的一部分

    slice = welcome[0:5] #range是一个左闭右开区间
    

字符串的template

以C为例:

printf("Hello %s", "Leo");

故效仿C的形式:

action = 'Hello'
name = 'Leo'

print('Hello %s' % 'Leo')
print('{0} {1}!'.format(action, name))
print("Pi : %.2f" % 3.14)

welcome = {action: "Hello", name: "Leo"}
print("{action} {name} !".format(**welcome))

Python中的数组——list

创建list

list1 = []  # This is an empty list, no any value
list2 = list()  # a way to create a list

number_list = [8, 6, 5, 7, 2]  # This is a list filled with numbers
mixed_list = [1, 'one', 2, "two", 3]  # This is a list with mixed value consist of number and strings

final_list = [number_list, mixed_list]  # This is a list consists of two different list

对list进行变换

  • 合并list

    final_list = number_list + mixed_list
    print(final_list)
    
  • 为list追加元素

    number_list.append([9, 10])
    print(number_list)
    
  • 为list进行排序(无返回值,升序)

    number_list1 = [3, 5, 6, 1, 2]
    number_list1.sort()
    print(number_list1)
    

append为O(1)算法,故最好只用1次(整体加入),不要让list反复遍历

  • 为list进行复制操作

    number_list2 = number_list1.copy()
    # 可以保留原list操作后的值
    

sort, append等方法皆为对原有对象的直接引用

  • 查找list上特定的值

    print(number_list1[0])  # 查找对应位置的单个值
    print(number_list1[0:2])  # 查找n个值,返回的是一个新的list
    print(number_list1[0:-2])  # 负数代表倒数顺序
    
  • 在指定位置上插入元素

    number_list1.insert(1, 9)  # 指定某位置的插入值,已有元素顺延 
    print(number_list1)
    
  • 删除指定位置的元素

    number_list1.remove(2)  # 移除该值,已有元素重新定序号,若没有此元素则报错
    del (number_list1[0:5:2])  # 在左闭右开区间内,每隔n个元素删除一个元素,且从范围内的第一个元素开始计数和删除,然后剩下的元素重新排序
    

Python中的只读集合——Tuple

简单来说,它就是一个只读的list,一旦创建之后,就只能访问它的值,而不能再对其修改,包括修改已有元素的值,以及添加删除元素,都不可以。

创建Tuple

empty = ()  # create an empty tuple
number_tuple = (1, 2, 3)  # use the elements to create a tuple directly
mix = tuple([1, 2, "Three"])  # use the list to pass its value to create a tuple

Tuple相关操作

# Tuple
from typing import Tuple

# 1. create the tuple
empty = ()  # create an empty tuple
number_tuple: tuple[int, int, int] = (1, 2, 3)  # use the elements to create a tuple directly
mix = tuple([1, 2, "Three"])  # use the list to pass its value to create a tuple


# 2. how to use the tuple
# print the tuple
print(number_tuple)

# add some tuples
print(number_tuple * 2)

# find some elements in the tuples
print(number_tuple[0])
print(number_tuple[0:2])
print(number_tuple[0:3:2])
print(3 in number_tuple)


# get length of the tuple
print(len(number_tuple))

# get the maximum of the tuple
print(max(number_tuple))

# get the minium of the tuple
print(min(number_tuple))

# if there is  a specific element?
print(3 in number_tuple)

# delete the whole tuple
del number_tuple

Python中的Dictionary

又称哈希表,指用某个具体的值而不是位置来指代另一个值,前者称为key,后者为value

创建Dictionary

# 1.1 Create an empty dictionary
empty_dictionary = {}

# 1.2 Create a dictionary directly
user = {'email': 'aoi@s1no1style.com', 'password': '1145141919810', 'ID': 1}

# 1.3 use the keyword dict() to create(not recommended)
another_user = dict({'email': 'aoi@'})

# 1.4 use another dictionary to extend it
user.update({'address': 'Tokyo, Japan'})

元素删除

# 2. delete the key and value in the dictionary
del user['password']
# del user  # of course it can also delete the whole dictionary
print(user)

# Caution: the key must be read-only, so only the value, tuple and dictionary could be the key.
# List can't be the key!

其他方法

print(user.values())  # get all the values in the dictionary
print(user.keys())  # get all the keys in the dictionary
print('email' in user)  # if there is a key like this in the dictionary?

分支语句和Boolean表达式

秉承着“一件事件只有一种做法”的原则,在Python里,我们只能使用if ... elif ... else在多个条件中选择

# if ... elif ... else
# remember, no switch ... case ...

num = 21
if num < 10:
    content = "&#123;0&#125; is less than 10".format(num)
    print(content)

elif 10 < num < 20:
    content = "&#123;0&#125; is greater than 10 and less than 20".format(num)
    print(content)

elif num in [10, 20]:
    content = "&#123;0&#125; is equal to 10 or 20".format(num)
    print(content)

else:
    content = "&#123;0&#125; is greater than 20".format(num)
    print(content)

一切空值都会被判断为false, None表示空

if __name__ == '__main__':
    # only be used to run some codes independently, maybe be used to debug

所以示例文件可以变换为:

# if ... elif ... else
# remember, no switch ... case ...


def conditional(func_num):
    if func_num < 10:
        content = "&#123;0&#125; is less than 10".format(func_num)
        print(content)

    elif 10 < func_num < 20:
        content = "&#123;0&#125; is greater than 10 and less than 20".format(func_num)
        print(content)

    elif func_num in [10, 20]:
        content = "&#123;0&#125; is equal to 10 or 20".format(func_num)
        print(content)

    else:
        content = "&#123;0&#125; is greater than 20".format(func_num)
        print(content)


if __name__ == '__main__':
    print('The Script "Conditional.py" is running.')
    num = int(input('Enter a number: '))
    conditional(num)

Python中的循环

在Python里,和其他编程语言类似,我们可以使用forwhile实现循环。

# for and while

# for num in [1, 2, 3, 4]:
# print(num)
for num in range(1, 5):
    if num == 2:
        print(num)
        break
else:
    print("Error!")
user = &#123;'id': 10, "Name": "Leo"&#125;
for info in user:
    print(info)  # info means the keys of the dictionary
    print(user[info])

value = 1

while value <= 10:
    if value % 2 == 0:
        value += 1
        continue

    print(value)
    value += 1

Python中的Comprehension

一个for循环配合if的特殊用法,简化代码用

# About the list comprehension

numbers = [i for i in range(1, 5) if i % 2 == 0]
print(numbers)

strings = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flatten = [value for key in strings for value in key]
print(flatten)

x_samples = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y_samples = [1, 2, 3, 4, 5, 6, 7, 8, 9]

need_points = [(x, y) for x in x_samples for y in y_samples if x != y]
print(need_points)

Python中的异常处理

在现实世界中,无论我们多么小心,编写的代码总是会因为一些外部的原因发生错误。例如,被粗心的开发者传递了错误的参数、要打开的文件被误删除了、操作系统发生了未知错误等等。哪怕这些问题都不存在,用户还可以在你的程序过程中通过Ctrl + C强制结束呢。所以,就像我们要一丝不苟的编写逻辑正确的代码一样,在错误处理上,我们同样马虎不得。

不过好在,相比哪些有很多种表达错误方式的语言,Python只有一种表达错误的方式,就是Exception,自然,处理错误的方式,也就只有一种了。

# Error Handling
# Remember, only the 'exception'
# Exception
# AttributeError
# IndexError
# NameError
# SyntaxError
# TypeError
# ValueError
# ZeroDivisionError

# So how to handle these errors?
try:
    3/0
except ZeroDivisionError:
    print("Divided by Zero!")
except NameError:
    print("Invalid Name!")
else:
    print("No Errors.")
finally:
    print("Clean up actions.")

# Divided by Zero!
# Clean up actions.

Python引入第三方代码

Python之所以广泛流行,依靠的当然不仅仅是它流畅简单的语法,还有在其背后给他站台撑腰的众多模块代码。依靠它们,可以让我们更简单的完成日常的开发工作。之前的例子里,我们使用的,都是属于Python核心功能的代码,因此,无须引入任何内容。

引入方式分为:Module 和 Package

# about import
# In Python, it consists of modules and packages
# Of course, a package includes some modules.
# For example:
# import this

import math as m
# from math import *       # Not recommended!
print(m.gcd(4, 6))  # 2

Python自定义函数

# about functions

def a_custom_function():
    pass  # just like the nop in asm


def add(*args):
    tmp = 0
    for i in args:
        tmp += i
    return tmp


def another_custom_function(*args, **kwargs):
    tmp = 0
    print(kwargs)
    for i in args:
        tmp += i

    for i in kwargs:
        tmp += kwargs[i]

    return tmp


print(add(1, 2, 3, 4, 5))  # 15
print(another_custom_function(1, 2, n1=4, n2=5, n3=6))

Python中的Class

# the beginning of the class

# take an example
class Person:
    """A general person class"""
    # Initial this class
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def wakeup(self, at):
        print("&#123;0&#125; wake up at &#123;1&#125; am".format(self.name, at))

    def __del__(self):
        print("This person &#123;0&#125; has been deleted".format(self.name))


mars = Person("Mars", 30)
eleven = mars

print(id(mars))
print(id(eleven))

del eleven
print("only 1 ref")
del mars

Class的继承和静态属性

class Person:
    """A general person class"""
    # Initial this class
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def wakeup(self, at):
        print("&#123;0&#125; wake up at &#123;1&#125; am".format(self.name, at))

    def __del__(self):
        print("This person &#123;0&#125; has been deleted".format(self.name))
        
from Person import Person


class Employee(Person):
    __counter = 0

    def __init__(self, name, age, work_id):
        Person.__init__(self, name, age)
        self.work_id = work_id
        Employee.__counter += 1

    def __str__(self):
        return "Employee"

    def __eq__(self, other):
        return self.name == other.name \
            and self.age == other.age \
            and self.work_id == other.work_id

from Employee import Employee
from Person import Person

mars = Employee('Mars', 30, 11)
eleven = Employee('Mars', 30, 11)
print(mars == eleven)  # if you want this value is true, you need to define the attribute "__eq__"
# print(Employee.__counter)

print(issubclass(Employee, Person))

print(isinstance(mars, Employee))
print(isinstance(mars, Person))

print(mars.__repr__())
print(mars.__str__())
# str use the repr, which include more information about developer
# str include more information about user, it can be written.

文章作者: Door
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Door !
  目录