2020-5-19
Python
官页 官页 Download Python 基础教程 - 菜鸟教程 Python 3 中文文档 W3school-Python 类/对象
Python 是由 Guido van Rossum 在八十年代末和九十年代初,在荷兰国家数学和计算机科学研究所设计出来的。 Python 的诞生是极具戏曲性的,据 Guido 自述记载,Python 语言是在圣诞节期间为了打发无聊的时间而开发的,之所以会选择 Python 作为该编程语言的名字,是因为 Guido 是 Monty Python 戏剧团的忠实粉丝。
快速入门
Python 语言参考手册 Python Crash Course for Non-Python Programmers - How to Get Started Quickly
变量和数据类型
字符串 (Strings)
(字符串方法)(https://www.w3school.com.cn/python/python_ref_string.asp)
# This is comment in Python
msg_from_computer = "Hello" # String
another_msg ='Hello in single quote' # This is also a String.
print(msg_from_computer + " World..!")
# Type will return the data type.
print(type(msg_from_computer)) # <type 'str'>. We will see the explanation of this later.取子串
s = 'hello world'
print(s[0:5]) # 输出 'hello'
print(s[:5]) # 输出 'hello'
print(s[:-3]) # 输出 'hello wo'
print(s[6:]) # 输出 'world'
print(s[-3:]) # rld字符串格式化
# 使用名称占位符
s2 = "xxxx {age} xxxx {name}".format(age=18, name="hangman")
print(s2) # xxxx 18 xxxx hangman
# 使用序号占位符,为空默认从左到右01234.。。
s3 = "xxxx {1} xxx{0}".format(value1,value2)
print(s3) # xxxx [9, 0] xxx(7, 8)
# 也可以混合使用
s4 = "xxxx {} XXX {name} xxx {}".format(value2,value1,name="s4")
print(s4) # xxxx [9, 0] XXX s4 xxx (7, 8)
import datetime
name = "zings"
age = 17
date = datetime.date(2019,7,18)
print(f'my name is {name}, this year is {date:%Y},Next year, I\'m {age+1}') # my name is zings, this year is 2019,Next year, I'm 18
数值 (Numbers)
2
2 * 3
2 ** 7 # 次方 2^7 = 128
(2 + 3) * 4
0.1 + 0.2 # 0.3
2 * 0.1 # 0.2列表 (List)
列表其实就是数组。在 Python 里,把它们叫作列表。列表是有序的。
numbers = ["one", "two", "three"]
numbers[0] # one
numbers[-1] # three. This is awesome. If we pass negative value Python will start from the end.
numbers[-2] # two
len(numbers) # 3. It just returns the length
numbers.append("four") # Append will add the element to the last. ["one", "two", "three", "four"]
numbers.insert(1, "wrong_one") # Insert will insert the particular value to the appropiate position. ["one", "wrong_one", "two", "three", "four"]
# Deleting a value is somewhat weird
del numbers[1] # Will delete the value in the appropiate position. "one", "two", "three", "four"]
# Pop will help you to remove the last element of an array
popped_element = numbers.pop()
print(popped_element) # four
print(numbers) # ["one", "two", "three"]
# Remove elements by value
numbers.remove("two") # ["one", "three"]. This will remove only the first occurence of an array.
# Sorting
alpha = ["z", "c", "a"]
alpha.sort()
print(alpha) # ["a", "c", "z"] Sorting is permanent. now `alpha` is sorted permanently
alpha.sort(reverse=True)
print(alpha) #["z", "c" , "a"] Reverse sorting.
alpha = ["z", "c", "a"]
print(sorted(alpha)) # ["a", "c", "z"] This will just return the sorted array. It wont save the sorted array to the variable itself.
print(alpha) # ["z", "c", "a"] As you can see, it's not sorted
# Reversing an array
nums = [10, 1, 5]
nums.reverse()
print(nums) # [5, 1, 10] It just reverses an array. It means it reads from last. It's not sorting it. It's just changing the chronological order.
# Slicing elements
alpha = ['a', 'b', 'c', 'd', 'e']
alpha[1:3] # ['b', 'c']. The first element is the starting index. And Python stops in the item before the second index.
alpha[2:5] # ['c', 'd', 'e']
alpha[:4] # [ 'a', 'b', 'c', 'd'] In this case, the first index is not present, so Python startes from the beginning.
alpha[:3] # ['a', 'b', 'c']
alpha[3:] # ['d', 'e'] In this case, last index is not present. So it travels till the end of the list.
alpha[:] # ['a', 'b', 'c', 'd', 'e'] There is no starting or ending index. So you know what happens. And this helps you in copying the entire array. I think I don't have to explain that if you copy the array, then any changes in the original array won't affect the copied array.
another_alpha = alpha # This布尔 (Bool)
True # First letter is caps 第一次字母大写
False
bool("some value") # Returns True
bool("") # Returns False
bool(1) # Returns True元组 (Tuples)
元组和列表类似,但是不可变的。也就是说,你不能给元组增加元素,只能读取元素。和列表一样,元组也是有序的。
nums = (1, 2, 3)
print(nums) # (1, 2, 3)
print(nums[0]) # 1
print(len(nums)) # 3
empty_tuple = () # empty tuple. Length is zero.
num = (1, ) # Note the trailing comma. When defining a single element in the tuple, consider adding a trailing comma.
num = (1)
print(type(num)) # <type 'int'> It won't return a tuple. Because there is no trailing comma.
# Creating a new tuple from the existing tuple
nums = (1, 2, 3)
char = ('a', )
new_tuple = nums + char
print(new_tuple) # (1, 2, 3, 'a')集合 (Sets)
集合是无序的,元素不可重复。
alpha = {'a', 'b', 'c', 'a'}
print(alpha) # set(['a', 'c', 'b']) As you can see, duplicates are removed in sets. And also the output is not ordered.
# Accessing items in set
# You can't access by index because Sets are unordered. You can access it only by loop. Don't worry about the for loop, we will get that in-depth in the following section.
for ele in alpha:
print(ele)
# To add element into the set
alpha.add('s')
# add can be used to insert only one element. If you want multiple elements, then update will be handy
alpha.update(['a', 'x', 'z']) # set(['a', 'c', 'b', 'x', 'z']) Remember duplicated are removed.
# Length of the alpha
len(alpha) # 5
# Remove the element from the set
alpha.remove('a')
alpha.discard('a') # It's safer to use discard than remove. Discard will never throw an error even if the element is not present in the set but remove will do.字典 (Dictionaries)
Python 中字典的形式是键-值 (类似Map) 字典是无序的。
user = {'id': 1, 'name': 'John wick', 'email': 'john@gmail.com'}
user['id'] # 1
user['name'] # John wick
# Length of the dict
len(user) # 3
# Add new key-value pair
user['age'] = 35
# To get all the keys
keys = user.keys() # ['id', 'name', 'email', 'age']. This will return a list.
# To get all the values
values = user.values() # [1, 'John wick', 'john@gmail.com']
# To delete a key
del user['age']
# Example of nested dict.
user = {
'id': 1,
'name': 'John wick',
'cars': ['audi', 'bmw', 'tesla'],
'projects': [
{
'id': 10,
'name': 'Project 1'
},
{
'id': 11,
'name': 'Project 2'
}
]
}
# We will see, how to loop through the dict in for loop section.if..else 条件分支
你可能已经知道 if..else 语句是怎样的,这里我们还是举个例子吧:
a = 5
b = 10
# See for the indentation. Indentations are very important in Python. Python will throw error if indentations are proper.
if a == 5:
print('Awesome')
# and is equivalent to &&
if a == 5 and b == 10:
print('A is five and b is ten')
# if else statement. This is same as most of the languages.
if a == 5:
print('A is five')
elif a == 6:
print('A is six')
elif a == 7:
print('A is seven')
else:
print('A is some number')
# or is equivalent to ||
if a < 6 or a == 10:
print('A should be less than 6 or should be equal to ten')
# not is equivalent to !
if not a == 10:
print('A is not equal to 10')
# This is the short-hand notation of if statement.
if a == 5: print('A is five')
# Short-hand for if-else statement.
print('A is five') if a == 5 else print('A is not five')while 循环
# The following while print till 5. Remember the indentation.
i = 0
while i <= 5:
print(i)
i += 1
# Using brake or continue in while loop
i = 0
while i <= 5:
print(i)
i += 1
if i == 2:
break # You can try using continue here
# Here comes the interesting part. While loop has else part. Else part will execute once the entire loop is completed.
i = 10
while i <= 15:
print(i)
i += 1
else:
print('Completed')
# Output
10
11
12
13
14
15
Completed
# But if you are using break in the loop, then Python will break out of the entire loop and it won't execute else part.
i = 10
while i <= 15:
print(i)
i += 1
if i == 13:
break
else:
print('Completed')
# Output
10
11
12For 循环
# For loops like for(i=0; i<5; i++) are not mostly used in Python. Instead, Python insists on iterating over items
arr = ['a', 'b', 'c', 'd', 'e']
for ele in arr: # Prints every element in an array
print(ele)
word = "python"
for char in word: # Prints every char in the word
print(char)
# You can use break, continue and else part in for-loop also.
# When talking about for loops, I noticed that most resources have also mentioned about range() function. (We will deal with functions later part of this article.)
# range() function will generates a sequence of numbers.
# range(start, stop, step)
# start - optional, the starting number. Default is 0. This number is included in the sequence
# stop - mandatory, the ending number. This number is excluded in the sequence
# step - optional, increments by. Default is 1.
range(3) # This code generates a sequences from 0 to 2.
range(1, 4) # This code generates a sequence from 1 to 3.
range(1, 8, 2) # This code generates a sequence with 1, 3, 5, 7
for ele in range(3): # Prints from 0 to 2.
print(ele)
# In the below example, you can see I have used range to iterate through an array with index.
for index in range(0, len(arr)):
print(arr[index])
dict = {'name': 'John wick'}
# You can iterate through a dictionary. items() will return both keys and values. You can also use keys() and values() if needed.
for key, value in dict.items():
print(key + " is " + value)
# You can also use a built-in function enumerate(). enumurate() will return a tuple with index. It is mostly used to add a counter to the iterable objects in Python.
for index, value in enumerate(arr):
print(value + " is present in " + str(index))
# 自定义步长
for i in range(0, len(list_str), 8) :
print(list_str[i])
print(list_str[i+1])
def 函数定义
def prints_hello_world():
print('Hello world from Python')
prints_hello_world()
# Return statement
def prints_something(something):
return something + ' from Python'
print(prints_something('Hello world'))
# If you pass wrong number of arguments like two or three arguments to this function then Python will throw an error.
print(prints_something())
# Default parameter. I think its common in most languages now.
def prints_something(something = 'Hello world'):
print(something + ' from Python')
# keyword arguments. You can pass explicitly which parameter should be matched. In this way, you don't have to send the arguments in order just explicitly mention the parameter name.
def movie_info(title, director_name, ratings):
print(title + " - " + director_name + " - " + ratings)
movie_info(ratings='9/10', director_name='David Fincher', title='Fight Club')
# Arbitrary number of arguments
# Sometimes, you dont know how many arguments are passed. In that case, you have ask Python to accept as many arguments as possible.
def languages(*names):
print(names) # ('Python', 'Ruby', 'JavaScript', 'Go'). This is a tuple.
return 'You have mentioned '+ str(len(names))+ ' languages'
print(languages('Python', 'Ruby', 'JavaScript', 'Go')) # You have mentioned 4 languages
def languages(fav_language, *names):
print(names) # ('Ruby', 'JavaScript', 'Go')
return 'My favorite language is ' + fav_language+ '. And Im planning to learn other '+ str(len(names))+ ' languages too'
print(languages('Python', 'Ruby', 'JavaScript', 'Go')) # My favorite language is Python. And Im planning to learn other 3 languages too
# Arbitrary keyword arguments
# These types of arguments are useful when you don't know what kind of parameters are passed. In the previous case, it's useful when you don't know how many number of parameters are passed but in this case, you don't know what type of information will be passed.
def user_info(**info):
print(info) # {'id': 1, 'name': 'Srebalaji', 'fav_language': ['Python', 'Ruby']} This is a dictionary
# Arbitrary keyword args will always expect to mention the parameters explicitly
user_info(id=1, name='Srebalaji', fav_language=['Python', 'Ruby'])
# The below code will throw error. There is no keyword arguments.
user_info(1, 'Srebalaji')
def user_info(id, name, **info):
print(info) # {'fav_language': ['Python', 'Ruby'], 'twitter_handle': '@srebalaji'}
user_info(1, 'Srebalaji', fav_language=['Python', 'Ruby'], twitter_handle='@srebalaji')
def readlines(self, hint: int = -1) -> List[AnyStr]: # -> 为函数添加**元数据**,描述函数的返回类型
pass
Lambda 表达式
# 一个 lambda 函数,它把参数 a 与参数 b 相乘并打印结果:
x = lambda a, b : a * b
print(x(5, 6))
# 一个 lambda 函数,它把参数 a、b 和 c 相加并打印结果:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
# 匿名函数
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
class 类定义
# Python is general purpose and also object oriented language.
# It's a convention that the class name starts with caps. But Python doesn't throw any error if you are not following it.
class Animal():
# This is the constructor.
# As you can see in every method of the class I have passed 'self' as the first parameter. The first parameter is always expected to be the current instance of the class and it is mandatory to pass the instance in the first parameter. And you can name that variable whatever you like.
def __init__(self, name):
self.name = name
def eat(self):
print(self.name +' eats')
def sleep(self):
print(self.name+' sleeps')
# Initiating a class
dog = Animal('harry')
dog.eat()
print(dog.name) # As you can see, 'name' attribute is also avaiable in public.
# It can even be modified.
dog.name = 'Rosie'
print(dog.name) # 'Rosie'
# Technically there is no way to make private attrbiutes in Python. But there are some techniques Python devs are using it. I will try to list out some.
# Protected attributes.
# These attributes can only be accessed within the class and also by the sub-class.
class Person():
# You can see that I have used different name for the first parameter.
def __init__(my_instance, name):
# 'name' attribute is protected.
my_instance._name = name
def reads(my_instance):
print(my_instance._name + ' reads')
def writes(my_object):
print(my_object._name + ' writes')
person1 = Person('Ram')
person1.reads()
# But the worst part is that instance of the class can still access and change it :P
print(person1._name) # 'Ram'
person1._name = 'I can still change.'
print(person1._name) # I can still change
# Protected can useful sometimes. Let's see how private attributes works. That can be a life saver sometimes.
class Person():
def __init__(self, name):
# 'name' attribute is private.
self.__name = name
def reads(self):
print(self.__name + ' reads')
def writes(self):
print(self.__name + ' writes')
# This is a private method. This can't be accessed outside the class.
def __some_helper_method():
print('Some helper method.')
person1 = Person('Ram')
person1.reads() # Ram reads
print(person1.name) # Will throw an error. 'Person' object has no attribute 'name'
print(person1.__name) # Will throw an error. 'Person' object has no attribute '__name'
# Private attributes can only be accessed within the class. So it's safe. But still there is a catch :P
print(person1._Person__name) # Ram.
# You can even change the value
person1._Person__name = 'Hari'
print(person1._Person__name) # Hari.
# But every dev know that accessing and modifying the private attributes is a bad practice. And Python doesn't really have a clear restriction to avoid it. So you got to trust your peers on this.
# Inheritance
class Animal():
def __init__(self, name):
self.name = name
def eat(self):
print('Animal eats')
def sleep(self):
print('Animal sleeps')
# Dog is a sub class of Animal
class Dog(Animal):
def __init__(self, name):
self.name = name
def eat(self):
print('Dog eats')
dog1 = Dog('harry')
dog1.eat() # Dog eats
dog1.sleep() # Animal sleepsfrom, import 模块
当你导入一个模块,Python 解析器对模块位置的搜索顺序是:
- 1、当前目录
- 2、如果不在当前目录,Python 则搜索在 shell 变量 PYTHONPATH 下的每个目录。
- 3、如果都找不到,Python 会查看默认路径。UNIX下,默认路径一般为/usr/local/lib/python/。
每个模块都有一个特殊属性 __dict__。 这是包含模块的符号表的字典。 修改此字典将实际改变模块的符号表,但是无法直接对 __dict__ 赋值 (你可以写 m.__dict__['a'] = 1,这会将 m.a 定义为 1,但是你不能写 m.__dict__ = {})。 不建议直接修改 __dict__。
# Modules helps us to organise code in Python. You can split code in different files and in folders and can access them when you wanted.
# Consider the below file. It has two functions.
# calculations.py
def add(a, b):
return a + b
def substract(a, b):
return a - b
# consider another file which we consider as a main file.
# main.py
import calculations
calculations.add(5, 10) # 15
calculations.substract(10, 3) # 7
# In the above example, you have imported the file and have accessed the functions in that.
# There are other ways of importing.
# You can change the method name if you want
import calculations as calc
calc.add(5, 10) # 15
# You can import specific functions you need.
# You can access the function directly. You don't want to mention the module.
from calculations import add
add(5, 10) # 15
# You can also import multiple functions
from calculations import add, multiple, divide
# You can import all the functions
from calculations import *
add(10, 15)
multiple(4, 5)
divide(10, 3)
# These will work for classes and variables too.它的导入语法, 其实是就看 from (文件名/模块名) 导入 as 为别名, 注意看from 关键词, 比 js 好理解
from win32com.client import Dispatch
import time
import VKEY_BOARD as V
from pynput import keyboard真假值
# According to Python docs, any object can be tested truthy or falsy.
# Below are the Truthy values
True
2 # Any numeric values other than 0
[1] # non-empty list
{'a': 1} # non-empty dict
'a' # non-empty string
{'a'} # non-empty Set
# Below are the Falsy values
False
None
0
0.0
[] # empty list
{} # empty dict
() # empty tuple
"" # empty string
range(0) # empty set
# You can evaluate any object to bool using
bool(any_object) # returns True or False异常处理
# The code which can raise exceptions can be wrapped in 'try' statement. 'except' will handle that exception.
try:
some_error_raised
except:
print('Exception handled')
# Every exception in Python will inherit from 'exception' class.
# In the below example, you can see that the 'NameError' is the exception class derived from the main 'Exception' class.
try:
some_error_raised
except Exception as e:
print('Exception raised')
print(e.__class__) # <class 'NameError'>
# 'else' block will execute if the code in the 'try' block has raised no exception. This will be useful in many situations.
try:
some_error_raised
except:
print('Exception handled')
else:
print('No error raised. You can resume your operation here') # this code will execute if no error is raised in the 'try' block
# final block
# Code in 'finally' block will execute no matter whether the exception is raised or not.
try:
some_error_raised
except Exception as e:
print('Exception raised')
else:
print('This will execute if no error is raised in try')
finally:
print('This code will run whether the code has error or not.')
# Raise your own exception. You can also create your own exception class inherited from Exception class.
try:
raise ZeroDivisionError # Python built-in exception class
except Exception as e:
print(e.__class__) # <class 'ZeroDivisionError'>
# Catch a specific exception.
try:
raise ZeroDivisionError # Python built-in exception class
except TypeError as e:
print('Only type error exception is captured')
except ZeroDivisionError as e:
print('Only zero division exception is captured')
except Exception as e:
print('Other execeptions')这种打开文件的方式
with open('data', 'r', encoding='utf-8') as f:
data = f.readlines()等价于下面
f = open('data', 'r', encoding='utf-8')
try:
data = f.readlines()
except:
pass
finally:
f.close()对比两段代码不难发现,使用with语句时,代码更加简洁,而且不用主动关闭文件,在with语句体退出时,会自动关闭文件,即便with语句体中发生了异常。
所有关键词
| 关键字 | 描述 |
|---|---|
| and | 逻辑运算符。 |
| as | 创建别名。 |
| assert | 用于调试。 |
| break | 跳出循环。 |
| class | 定义类。 |
| continue | 继续循环的下一个迭代。 |
| def | 定义函数。 |
| del | 删除对象。 |
| elif | 在条件语句中使用,等同于 else if。 |
| else | 用于条件语句。 |
| except | 处理异常,发生异常时如何执行。 |
| False | 布尔值,比较运算的结果。 |
| finally | 处理异常,无论是否存在异常,都将执行一段代码。 |
| for | 创建 for 循环。 |
| from | 导入模块的特定部分。 |
| global | 声明全局变量。 |
| if | 写一个条件语句。 |
| import | 导入模块。 |
| in | 检查列表、元组等集合中是否存在某个值。 |
| is | 测试两个变量是否相等。 |
| lambda | 创建匿名函数。 |
| None | 表示 null 值。 |
| nonlocal | 声明非局部变量。 |
| not | 逻辑运算符。 |
| or | 逻辑运算符。 |
| pass | null 语句,一条什么都不做的语句。 |
| raise | 产生异常。 |
| return | 退出函数并返回值。 |
| True | 布尔值,比较运算的结果。 |
| try | 编写 try...except 语句。 |
| while | 创建 while 循环。 |
| with | 用于简化异常处理。 |
| yield | 结束函数,返回生成器。 |
慢速出门 :)
特殊属性
语言实现为部分对象类型添加了一些特殊的只读属性,它们具有各自的作用。 其中一些并不会被 dir() 内置函数所列出。
简而言之, 对象元属性
object.__dict__
一个字典或其他类型的映射对象,用于存储对象的(可写)属性。
instance.__class__
类实例所属的类。
class.__bases__
由类对象的基类所组成的元组。
definition.__name__
类、函数、方法、描述器或生成器实例的名称。
definition.__qualname__
类、函数、方法、描述器或生成器实例的 qualified name。
class.__mro__
此属性是由类组成的元组,在方法解析期间会基于它来查找基类。
class.mro()此方法可被一个元类来重载,以为其实例定制方法解析顺序。 它会在类实例化时被调用,其结果存储于 mro 之中。
class.__subclasses__()
每个类都存有对直接子类的弱引用列表。本方法返回所有存活引用的列表。列表的顺序按照子类定义的排列。
__module__
它用于存储当前类所在的模块名称。
if __name__ == '__main__':
内置函数
装饰器
装饰器是一种函数,它接受一个函数作为参数,并返回一个新的函数或修改原来的函数。 装饰器的语法使用 @decorator_name 来应用在函数或方法上。 Python 还提供了一些内置的装饰器,比如 @staticmethod 和 @classmethod,用于定义静态方法和类方法。
# 入参 original_function 是原始函数
def decorator_function(original_function):
def wrapper(*args, **kwargs):
# 这里是在调用原始函数前添加的新功能
before_call_code()
result = original_function(*args, **kwargs)
# 这里是在调用原始函数后添加的新功能
after_call_code()
return result
return wrapper
# 使用装饰器
@decorator_function
def target_function(arg1, arg2):
pass # 原始函数的实现集合的处理
Python快速入门&慢速出门 Python 列表(List) - 菜鸟教程
标准函数列表
| 方法 | 说明 |
|---|---|
len(iterable) | 返回可迭代对象的长度(元素个数)。 |
max(iterable) | 返回可迭代对象中的最大值。 |
min(iterable) | 返回可迭代对象中的最小值。 |
sum(iterable) | 返回可迭代对象中元素的总和。 |
sorted(iterable) | 返回可迭代对象的排序副本。 |
enumerate(iterable) | 将可迭代对象的元素和它们的索引配对。 |
zip(*iterables) | 将多个可迭代对象中的元素依次配对为元组。 |
filter(function, iterable) | 使用函数过滤可迭代对象的元素。 |
map(function, iterable) | 使用函数转换可迭代对象的元素。 |
reduce(function, iterable) | 从左到右地将函数累积地应用于可迭代对象的元素。 |
all(iterable) | 如果可迭代对象中的所有元素都为真,则返回 True。 |
any(iterable) | 如果可迭代对象中的任何元素为真,则返回 True。 |
join(iterable) | 将字符串可迭代对象的元素连接成一个字符串。 |
list(iterable) | 将可迭代对象转换为列表。 |
set(iterable) | 将可迭代对象转换为集合,去除重复的元素。 |
dict(iterable) | 将可迭代对象的元素(键值对)转换为字典。 |
tuple(iterable) | 将可迭代对象转换为元组。 |
any(iterable) | 如果可迭代对象中的任何元素为真,则返回 True。 |
reversed(iterable) | 返回可迭代对象的反向迭代器。 |
列表
Python 有一组可以在列表上使用的内建方法。
| 方法 | 描述 |
|---|---|
| append() | 在列表的末尾添加一个元素 |
| clear() | 删除列表中的所有元素 |
| copy() | 返回列表的副本 |
| count() | 返回具有指定值的元素数量。 |
| extend() | 将列表元素(或任何可迭代的元素)添加到当前列表的末尾 |
| index() | 返回具有指定值的第一个元素的索引 |
| insert() | 在指定位置添加元素 |
| pop() | 删除指定位置的元素 |
| remove() | 删除具有指定值的项目 |
| reverse() | 颠倒列表的顺序 |
| sort() | 对列表进行排序 |
基本操作
取子数组
# 第一项的索引为 0。搜索将从索引 2(包括)开始,到索引 5(不包括)结束。
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
# ['cherry', 'orange', 'kiwi']
# 等同, 只有前三个
print(thislist[:3])
# ['apple', 'banana', 'cherry']
# 返回从索引 -4(包括)到索引 -1(排除)
print(thislist[-4:-1])
# ['orange', 'kiwi', 'melon']
# 只要 remaining_chapters 数组元素中的 title_kw 元素
end_kw = [c["title_kw"] for c in remaining_chapters]
# 数组连接
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
result = arr1 + arr2
print(result) # [1, 2, 3, 4, 5, 6]
arr1.extend(arr2)
print(arr1)# [1, 2, 3, 4, 5, 6]增删改查
# 追加项目
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
# 插入项目作为第二个位置
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
# `remove()` 方法删除指定的项目:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
# `pop()` 方法删除指定的索引(如果未指定索引,则删除最后一项):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
# 删除指定的索引:
del thislist[0]
print(thislist)
# `del` 关键字也能完整地删除列表:
del thislist
print(thislist)
# 查询
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")复制
thislist = ["apple", "banana", "cherry"]
# 使用 `copy()` 方法来复制列表:
mylist = thislist.copy()
print(mylist)
# 另一种方法是使用内建的方法 `list()`。
# 使用 `list()` 方法复制列表:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
分组
# 原生
def group_by(arr, key_func):
"""基础分组函数"""
result = {}
for item in arr:
key = key_func(item)
if key not in result:
result[key] = []
result[key].append(item)
return result
# 测试
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = group_by(data, lambda x: 'even' if x % 2 == 0 else 'odd')
print(result)
# 输出: {'odd': [1, 3, 5, 7, 9], 'even': [2, 4, 6, 8, 10]}字典(Dictionary)
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
print(thisdict)Python 提供一组可以在字典上使用的内建方法。
| 方法 | 描述 |
|---|---|
| clear() | 删除字典中的所有元素 |
| copy() | 返回字典的副本 |
| fromkeys() | 返回拥有指定键和值的字典 |
| get() | 返回指定键的值 |
| items() | 返回包含每个键值对的元组的列表 |
| keys() | 返回包含字典键的列表 |
| pop() | 删除拥有指定键的元素 |
| popitem() | 删除最后插入的键值对 |
| setdefault() | 返回指定键的值。如果该键不存在,则插入具有指定值的键。 |
| update() | 使用指定的键值对字典进行更新 |
| values() | 返回字典中所有值的列表 |
基本操作
# 获取 "model" 键的值:
x = thisdict["model"]
x = thisdict.get("model")
# 遍历键 key
for x in thisdict:
print(thisdict[x])
# 遍历值 value
for x in thisdict.values():
print(x)
# 通过使用 items() 函数遍历 键 和 值:
for x, y in thisdict.items():
print(x, y)
# 检查键
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
# 删除
thisdict.pop("model")
del thisdict["model"]
# 使用 `copy()` 方法来复制字典:
mydict = thisdict.copy()
print(mydict)
# 使用 `dict()` 方法创建字典的副本:
mydict = dict(thisdict)
print(mydict)标准库
Python 标准库 菜鸟教程 - Python 文件I/O
常用模块说明
- os 模块:os 模块提供了许多与操作系统交互的函数,例如创建、移动和删除文件和目录,以及访问环境变量等。
- sys 模块:sys 模块提供了与 Python 解释器和系统相关的功能,例如解释器的版本和路径,以及与 stdin、stdout 和 stderr 相关的信息。
- time 模块:time 模块提供了处理时间的函数,例如获取当前时间、格式化日期和时间、计时等。
- datetime 模块:datetime 模块提供了更高级的日期和时间处理函数,例如处理时区、计算时间差、计算日期差等。
- random 模块:random 模块提供了生成随机数的函数,例如生成随机整数、浮点数、序列等。
- math 模块:math 模块提供了数学函数,例如三角函数、对数函数、指数函数、常数等。
- re 模块:re 模块提供了正则表达式处理函数,可以用于文本搜索、替换、分割等。
- json 模块:json 模块提供了 JSON 编码和解码函数,可以将 Python 对象转换为 JSON 格式,并从 JSON 格式中解析出 Python 对象。
- urllib 模块:urllib 模块提供了访问网页和处理 URL 的功能,包括下载文件、发送 POST 请求、处理 cookies 等。
完整列表
platform--- 获取底层平台的标识数据- 并发执行
contextvars上下文变量- 网络和进程间通信
- 互联网数据处理
- 结构化标记处理工具
html--- 超文本标记语言支持html.parser--- 简单的 HTML 和 XHTML 解析器html.entities--- HTML 一般实体的定义- XML处理模块
xml.etree.ElementTree--- ElementTree XML APIxml.dom--- 文档对象模型 APIxml.dom.minidom--- 最小化的 DOM 实现xml.dom.pulldom--- 支持构建部分 DOM 树xml.sax--- 支持 SAX2 解析器xml.sax.handler--- SAX 处理程序的基类xml.sax.saxutils--- SAX 工具集xml.sax.xmlreader--- 用于 XML 解析器的接口xml.parsers.expat--- 使用 Expat 的快速 XML 解析
- 互联网协议和支持
webbrowser--- 方便的Web浏览器控制器cgi--- 通用网关接口支持cgitb--- 用于 CGI 脚本的回溯管理器wsgiref--- WSGI 工具和引用的实现urllib--- URL 处理模块urllib.request--- 用于打开 URL 的可扩展库urllib.response--- urllib 使用的 Response 类urllib.parse用于解析 URLurllib.error--- urllib.request 引发的异常类urllib.robotparser--- robots.txt 语法分析程序http--- HTTP 模块http.client--- HTTP 协议客户端ftplib--- FTP 协议客户端poplib--- POP3 协议客户端imaplib--- IMAP4 协议客户端nntplib--- NNTP 协议客户端smtplib---SMTP协议客户端smtpd--- SMTP 服务器telnetlib— Telnet 客户端uuid--- RFC 4122 定义的UUID对象socketserver--- 用于网络服务器的框架http.server--- HTTP 服务器http.cookies--- HTTP状态管理http.cookiejar—— HTTP 客户端的 Cookie 处理xmlrpc--- XMLRPC 服务端与客户端模块xmlrpc.client--- XML-RPC 客户端访问xmlrpc.server--- 基本 XML-RPC 服务器ipaddress--- IPv4/IPv6 操作库
- 多媒体服务
- 国际化
- 程序框架
- Tk图形用户界面(GUI)
- 开发工具
typing--- 类型标注支持pydoc--- 文档生成器和在线帮助系统doctest--- 测试交互性的Python示例unittest--- 单元测试框架unittest.mock--- 模拟对象库unittest.mock上手指南- 2to3 - 自动将 Python 2 代码转为 Python 3 代码
test--- Python回归测试包test.support--- Utilities for the Python test suitetest.support.script_helper--- Utilities for the Python execution tests
- 调试和分析
- 软件打包和分发
- Python运行时服务
sys--- 系统相关的参数和函数sysconfig--- Provide access to Python’s configuration informationbuiltins--- 内建对象__main__--- 顶层脚本环境warnings—— 警告信息的控制dataclasses--- 数据类contextlib--- 为with语句上下文提供的工具abc--- 抽象基类atexit--- 退出处理器traceback--- 打印或检索堆栈回溯__future__--- Future 语句定义gc--- 垃圾回收器接口inspect--- 检查对象site—— 站点专属的配置钩子
- 自定义 Python 解释器
- 导入模块
- Python 语言服务
parser--- 访问 Python 解析树ast--- 抽象语法树symtable——访问编译器的符号表symbol--- 与 Python 解析树一起使用的常量token--- 与Python解析树一起使用的常量keyword--- 检验Python关键字tokenize— 对 Python 代码使用的标记解析器tabnanny--- 模糊缩进检测pyclbr--- Python 模块浏览器支持py_compile--- 编译 Python 源文件compileall--- Byte-compile Python librariesdis--- Python 字节码反汇编器pickletools--- pickle 开发者工具集
- 杂项服务
- Windows系统相关模块
- Unix 专有服务
- 被取代的模块
- 未创建文档的模块
print 函数 模版参数
| 格式符 | 表示 |
| %s | 字符串 |
| %d | 十进制整数 |
| %f | 浮点型 |
| %c | 字符型 |
| %u | 无符号十进制整数 |
| %o | 八进制 |
| %x | 十六进制 |
| %e | 科学计数法 |
| 格式符 | 表示 |
| %.2f | 保留两位小数 |
| %04d | 输出前面4个字符空间补零 |
| %4d | 右对齐前面留出4个字符空间 |
| %-4d | 左对齐并占用4个字符空间 |
x = 123
print('%d'%x)
#输出:123
print('这有一个整数%d'%666)
#输出:这有一个整数666
print('%.2f'%3.141592)
#输出:3.14
print('%e'%14332231433223)
#输出:1.433223e+13
print('%04d'%99)
#输出:000099
print('%9s'%'hahaha')
#输出: hahaha(注意左侧有多个空格)多环境管理 (venv)
创建环境
# 基础创建(当前目录)
python3 -m venv langchain
python3 -m venv langchain # 推荐命名
python3 -m venv .langchain # 隐蔽命名(.开头,常被IDE自动识别)
# 指定Python版本 & 路径
python3.9 -m venv ~/envs/langchain
# 查找所有环境 # 假设环境存于 ~/envs/
ls ~/envs/
激活环境
| 系统 | 命令 |
|---|---|
| Windows (CMD/PowerShell) | venv\Scripts\activate |
| macOS / Linux (Bash/Zsh) | source venv/bin/activate |
| Fish Shell | source venv/bin/activate.fish |
# windows
langchain\Scripts\activate
# linux
source ~/langchain/bin/activate
依赖管理(激活后操作)
# 安装包
pip install requests
pip install -i https://mirrors.aliyun.com/pypi/simple 包名 # 国内加速
# 查看已安装包
pip list
pip show 包名 # 查看单个包详情
# 导出/导入依赖
pip freeze > requirements.txt # 导出当前环境依赖
pip install -r requirements.txt # 重建相同环境
# 升级pip(推荐首次激活后执行)
python -m pip install --upgrade pip退出与删除
# 退出当前虚拟环境
deactivate
# 删除虚拟环境(直接删除目录)
# Linux/macOS
rm -rf venv
# Windows (CMD)
rmdir /s venv
# Windows (PowerShell)
Remove-Item -Recurse -Force venvPython 调用 DLL
ctypes 库文档 fundamental-data-types 基础数据类型 https://pyopdll.readthedocs.io/zh/latest/#welcome-to-pyopdll
Python可以直接调用C++的动态链接库(DLL)。Python提供了一个名为ctypes的内置模块,它允许你加载C函数并在Python中调用它们。
// example.cpp
extern "C" {
int add(int a, int b) {
return a + b;
}
}
import ctypes
# 加载DLL
dll = ctypes.CDLL('./example.dll')
# 指定函数参数和返回类型
dll.add.argtypes = [ctypes.c_int, ctypes.c_int]
dll.add.restype = ctypes.c_int
# 调用DLL中的函数
result = dll.add(3, 4)
print(result)
PIP 工具
pip 是 Python 包管理工具, 该工具提供了对Python 包的查找, 下载, 安装, 卸载的功能;
pip show pip 显示信息
配置源
PIP
-
Unix 和 MacOS:
- 全局配置:
/etc/pip.conf或/etc/pip/pip.conf - 用户配置:
~/.pip/pip.conf或~/.config/pip/pip.conf
- 全局配置:
-
Windows:
- 全局配置:通常在 Python 安装目录下的
Lib\site-packages\pip\pip.ini - 用户配置:
C:\Users\<username>\pip\pip.ini或C:\Users\<username>\AppData\Roaming\pip\pip.ini
- 全局配置:通常在 Python 安装目录下的
-
配置文件
[global]
timeout=30
index-url=https://pypi.tuna.tsinghua.edu.cn/simple/
extra-index-url=
https://mirrors.aliyun.com/pypi/simple/
https://pypi.mirrors.ustc.edu.cn/simple/
[install]
trusted-host=
pypi.tuna.tsinghua.edu.cn
mirrors.aliyun.com
pypi.mirrors.ustc.edu.cn
如果使用 http 链接,需要指定
trusted-host参数:
- 或者使用命令
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip config set global.trusted-host mirrors.aliyun.com
查看更改后的镜像源
pip config list其他国内镜像源
中国科学技术大学 : https://pypi.mirrors.ustc.edu.cn/simple 豆瓣:http://pypi.douban.com/simple/ 阿里云:http://mirrors.aliyun.com/pypi/simple/ https://mirrors.aliyun.com/pypi/simple/ 官方源 https://pypi.python.org/simple
–trusted-host pypi.python.org
conda
conda 默认源可能速度比较慢 可以添加其他源
## 清华源
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/
## 中科大
conda config --add channels https://mirrors.ustc.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.ustc.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/conda-forge/
conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/msys2/
conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/bioconda/
conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/menpo/
conda config --set show_channel_urls yes // 在包后面显示来源
或者修改配置文件
vi ~/.condarc
channels:
- defaults
show_channel_urls: true
default_channels:
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud默认路径
一般情况下 pip 安装包的默认路径是C盘下:%appdata%\Python\site-packages ,Python 附带的指令一般在 %appdata%\Python\Scripts 下; 使用 python -m site 可以看到 USER_BASE 和 USER_SITE 在 C 盘
下
python -m site -helpsite.py文件位置- 找到文件中的 USER_SITE 和 USER_BASE
# for distutils.commands.install
# These values are initialized by the getuserbase() and getusersitepackages()
# functions, through the main() function when Python starts.
USER_SITE = "F:\\pip_local_repository\\"
USER_BASE = "C:\\Users\\yang\\AppData\\Local\\Programs\\Python"
注意安装目录是 C:\\Users\\yang\\AppData\\Local\\Programs\\Python
'C:\\Users\\yang\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\yang\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\yang\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\yang\\AppData\\Local\\Programs\\Python\\Python39',配置代理
无代理方式 pip install <package_name> —proxy=” pip install apngasm-python —proxy=”
设置代理 pip install <package_name> —proxy=http://proxy_server:port
pip install langchain_milvus —proxy=‘https://mirrors.aliyun.com/pypi/simple/‘
证书信任
若报错 为该源未添加信任,追加 –trusted-host pypi.douban.com
pip install PyMySQL --trusted-host https://pypi.org/simple
pip install PyMySQL -i https://pypi.tuna.tsinghua.edu.cn/simple pip -U --trusted-host pypi.tuna.tsinghua.edu.cn
pip install PyMySQL -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.comopencv
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
IDE (PyCharm)
默认创建项目, 会自己创建虚拟环境..
um.. 第一件事 就是设置解释器:
file -> setting -> priject:xx -> python interpreter 选 Anaconda 的解释器
IDE (VsCode)
- 调试第三方库代码
.vscode\launch.json//“justMyCode”: false,
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"justMyCode": false,
"console": "integratedTerminal"
}
]
}