自学内容网 自学内容网

python基础巩固

基本数据类型

可以用isinstance来判断

a=111
isinstance(a,int)
True

数值运算:

>>> 2 / 4  # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余 
2

Python 字符串不能被改变。向一个索引位置赋值,比如 word[0] = ‘m’ 会导致错误。

tup1 = () # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号
Sets(集合)

集合(set)是一个无序不重复元素的集。
基本功能是进行成员关系测试和消除重复元素。
可以使用大括号 或者 set() 函数创建 set 集合,注意:创建一个空集合必须用 set() 而不是 { },因为{ }是用来创建一个空字典。

>>> student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
>>> print(student)   # 重复的元素被自动去掉
{'Jim', 'Jack', 'Mary', 'Tom', 'Rose'}
>>> 'Rose' in student  # membership testing(成员测试)
True
>>> # set可以进行集合运算
... 
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'a', 'b', 'c', 'd', 'r'}
>>> a - b     # a和b的差集
{'b', 'd', 'r'}
>>> a | b     # a和b的并集
{'l', 'm', 'a', 'b', 'c', 'd', 'z', 'r'}
>>> a & b     # a和b的交集
{'a', 'c'}
>>> a ^ b     # a和b中不同时存在的元素
{'l', 'm', 'b', 'd', 'z', 'r'}

Dictionaries(字典)

字典(dictionary)是 Python 中另一个非常有用的内置数据类型。
字典是一种映射类型(mapping type),它是一个无序的键值对(key-value)集合。
关键字(key)必须使用不可变类型,也就是说list和包含可变类型的 tuple 不能做关键字。
在同一个字典中,关键字(key)必须互不相同。

>>> dic = {}  # 创建空字典
>>> tel = {'Jack':1557, 'Tom':1320, 'Rose':1886}
>>> tel
{'Tom': 1320, 'Jack': 1557, 'Rose': 1886}
>>> tel['Jack']   # 主要的操作:通过key查询
1557
>>> del tel['Rose']  # 删除一个键值对
>>> tel['Mary'] = 4127  # 添加一个键值对
>>> tel
{'Tom': 1320, 'Jack': 1557, 'Mary': 4127}
>>> list(tel.keys())  # 返回所有key组成的list
['Tom', 'Jack', 'Mary']
>>> sorted(tel.keys()) # 按key排序
['Jack', 'Mary', 'Tom']
>>> 'Tom' in tel       # 成员测试
True
>>> 'Mary' not in tel  # 成员测试
False

构造函数 dict() 直接从键值对 sequence 中构建字典,当然也可以进行推导,如下:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'jack': 4098, 'sape': 4139, 'guido': 4127}

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

>>> dict(sape=4139, guido=4127, jack=4098)
{'jack': 4098, 'sape': 4139, 'guido': 4127}

在交互模式中,最后被输出的表达式结果被赋值给变量 _ 。例如:
此处, _ 变量应被用户视为只读变量。

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

在这里插入图片描述

在这里插入图片描述

字典 update() 方法
dict = {'Name': 'W3CSchool', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("更新字典 dict : ", dict)

更新字典 dict :  {'Name': 'W3CSchool', 'Age': 7, 'Sex': 'female'}
集合的基本操作
thisset = set(("Google", "W3Cschool", "Taobao"))
thisset.add("Baidu")   # 1、添加元素:s.add( x )
thisset.update({1,3})  # 2、添加元素:s.update( x )
thisset.discard("Facebook")  # 3、移除元素:s.discard( x ) 不存在不会发生错误 
x = thisset.pop()  # 4 随机删除集合中的一个元素  x = Google   thisset = ("W3Cschool", "Taobao")
列表
方法描述
list.insert(i, x)在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引,例如 a.insert(0, x) 会插入到整个列表之前,而 a.insert(len(a), x) 相当于 a.append(x)
list.remove(x)删除列表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误。
list.index(x)返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。
list.pop([i])从列表的指定位置删除元素,并将其返回。如果没有指定索引,a.pop()返回最后一个元素。元素随即从列表中被删除。(方法中 i 两边的方括号表示这个参数是可选的,而不是要求你输入一对方括号,你会经常在 Python 库参考手册中遇到这样的标记。)
list.count(x)返回 x 在列表中出现的次数。
list.sort()对列表中的元素进行排序。
list.reverse()倒排列表中的元素。
***del 语句***
使用 del 语句可以从一个列表中依照索引(而不是值)来删除一个元素。这与使用 pop() 返回一个值不同。
可以用 del 语句从列表中删除一个切片,或清空整个列表(我们以前介绍的方法是给该切片赋一个空列表)。例如:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

条件控制

在 Python 中没有 switch – case 语句,但在python3.10中添加了用法类似的match-case语句。

(关于模式匹配还有更多的用法,可以参考PEP636进行详细的学习。)
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the Internet"

上述代码等价于:

def http_error(status):
    if status == 400:
        return "Bad request"
    elif status == 404:
        return "Not found"
    elif status == 418:
        return "I'm a teapot"
    else:
        return "Something's wrong with the Internet"
循环
while 判断条件:
    statements

n = 100
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter     
    counter += 1  
print('Sum of 1 until %d: %d' % (n,sum)) 

可以结合 range() 和 len() 函数以遍历一个序列的索引,如下所示:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
遍历技巧

在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来:

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

同时遍历两个或更多的序列,可以使用 zip() 组合:

>>> 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.

要反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数:

>>> for i in reversed(range(1, 10, 2)):
...     print(i)

97531

要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple、banana、orange、pear

OS 文件/目录方法
序号方法及描述
os.removedirs(path)递归删除目录。
os.getcwd()返回当前工作目录。
os.remove(path)删除路径为 path 的文件。如果 path 是一个文件夹,将抛出 OSError; 查看下面的 rmdir() 删除一个 directory。
字典更新和合并

合并 (|) 与更新 (|=) 运算符已被加入内置的 ​dict ​类。 它们为现有的 dict.update 和 {**d1, **d2} 字典合并方法提供了补充。

>>> x = {"key1": "value1 from x", "key2": "value2 from x"}
>>> y = {"key2": "value2 from y", "key3": "value3 from y"}
>>> x | y
{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}
>>> y | x
{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}

xx = {"key1": "value1 from x", "key2": "value2 from x"}
yy = {"key6": "value2 from y", "key7": "value3 from y"}
yy |= xx
print(yy, xx)
{'key6': 'value2 from y', 'key7': 'value3 from y', 'key1': 'value1 from x', 'key2': 'value2 from x'}
线程
import threading
import time


# 为线程定义一个函数
def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("%s: %s" % (threadName, time.ctime(time.time())))


# 创建两个线程
try:
    thread1 = threading.Thread(target=print_time, args=("Thread-1", 1,))
    thread1.start()
    thread2 = threading.Thread(target=print_time, args=("Thread-2", 2,))
    thread2.start()
except:
    print("Error: 无法启动线程")
线程优先级队列( Queue)

Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括 FIFO(先入先出)队列 Queue,LIFO(后入先出)队列 LifoQueue,和优先级队列 PriorityQueue。

这些队列都实现了锁原语,能够在多线程中直接使用,可以使用队列来实现线程间的同步。

Queue 模块中的常用方法:

Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回 True,反之 False
Queue.full() 如果队列满了,返回 True,反之 False
Queue.full 与 maxsize 大小对应
Queue.get([block[, timeout]]) 获取队列,timeout 等待时间
Queue.get_nowait() 相当 Queue.get(False)
Queue.put(item) 写入队列,timeout 等待时间
Queue.put_nowait(item) 相当 Queue.put(item, False)
Queue.task_done() 在完成一项工作之后,Queue.task_done() 函数向任务已经完成的队列发送一个信号
Queue.join() 实际上意味着等到队列为空,再执行别的操作

#!/usr/bin/python3

import queue
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        print ("开启线程:" + self.name)
        process_data(self.name, self.q)
        print ("退出线程:" + self.name)

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print ("%s processing %s" % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1

# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# 填充队列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass

# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
for t in threads:
    t.join()
print ("退出主线程")

JSON 数据解析

json.dumps(): 对数据进行编码 【字典转字符串】。
json.loads(): 对数据进行解码 【字符串转字典】。

import json

# Python 字典类型转换为 JSON 对象
data1 = {
    'no': 1,
    'name': 'W3CSchool',
    'url': 'http://www.w3cschool.cn'
}

json_str = json.dumps(data1)
print("Python 原始数据:", repr(data1))
print("JSON 对象:", isinstance(json_str, str), json_str)

# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print("data2['name']: ", data2['name'], data2.get('name'))
print("data2['url']: ", data2['url'])

日期和时间
#!/usr/bin/python3
import time;  # 引入time模块

ticks = time.time()
print ("当前时间戳为:", ticks) 

当前时间戳为:1459996086.7115328

# 格式化成2020-03-20 11:45:39形式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
2020-04-07 10:29:46

Python 中时间日期格式化符号:

%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24 小时制小时数(0-23)
%I 12 小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地 A.M. 或 P.M. 的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始


原文地址:https://blog.csdn.net/Evan_Ada/article/details/140463739

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!