Fork me on GitHub

Python基础

基础数据类型

  • Number(数字)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Set(集合)
  • Dictionary(字典)

六个标准数据类型中:

  • 不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
  • 可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。

Number(数字)

Python3 支持 int、float、bool、complex(复数)

使用 type() 函数来查询变量所指的对象类型。

a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))
# <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

取整

1、向下取整

向下取整直接用内建的 int() 函数即可:

a = 3.75
print(int(a))
# output: 3

2、四舍五入

对数字进行四舍五入用 round() 函数:

用法:

# n保留小数位数,默认保留整数部分
# round(a,n)
a = 3.25
print(round(a))
# output: 3

3、向上取整

向上取整需要用到 math 模块中的 ceil() 方法:

import math
a = 3.25
print(math.ceil(a))
# output: 4

进制转换

# 将一个整数对象为二进制的字符串
bin()
# 将一个整数对象为十进制的字符串
oct()
# 将一个整数对象为十六进制的字符串
hex()
# 转换一个[0, 255]之间的整数为对应的ASCII字符
chr()
# 将一个ASCII字符转换为对应整数
ord()
# 二进制转十进制
int(string_num, 2)
# 二进制转16进制
t = input()
print(hex(int(t,2)))

不同进制相互转换实列

import os, sys
# global definition
# base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord('A') + 6)]
# bin2dec
# 二进制 to 十进制: int(str,n=10)
def bin2dec(string_num):
return str(int(string_num, 2))
# hex2dec
# 十六进制 to 十进制
def hex2dec(string_num):
return str(int(string_num.upper(), 16))
# dec2bin
# 十进制 to 二进制: bin()
def dec2bin(string_num):
num = int(string_num)
mid = []
while True:
if num == 0:
break
num, rem = divmod(num, 2)
mid.append(base[rem])
return ''.join([str(x) for x in mid[::-1]])
# dec2hex
# 十进制 to 八进制: oct()
# 十进制 to 十六进制: hex()
def dec2hex(string_num):
num = int(string_num)
mid = []
while True:
if num == 0:
break
num, rem = divmod(num, 16)
mid.append(base[rem])
return ''.join([str(x) for x in mid[::-1]])
def dec2oth(num):
mid = []
while True:
if num == 0:
break
num, rem = divmod(num, 26)
# print(rem)
mid.append(base[rem])
# print(mid)
return ''.join([str(x) for x in mid[::-1]])
base = [chr(x) for x in range(ord('A'), ord('A') + 26)]
# hex2tobin
# 十六进制 to 二进制: bin(int(str,16))
def hex2bin(string_num):
return dec2bin(hex2dec(string_num.upper()))
# bin2hex
# 二进制 to 十六进制: hex(int(str,2))
def bin2hex(string_num):
return dec2hex(bin2dec(string_num))

String(字符串)

字符串用单引号或双引号括起来

字符串的截取用法如下:

# start 开始下标,默认为0
# end 结束下标,默认len()
# step 步长,默认为1,step<0时,倒序,start默认为-1,end默认为-len()-1
str[start:end:step]

索引值以 0 为开始值,-1 为从末尾的开始位置。

类型判断

#isdigit 函数判断是否数字
print(str.isdigit())
#用isalpha 判断是否字母
print(str.isalpha())
#isalnum 判断是否数字和字母的组合
print(str.isalnum())
#islower 判断是否小写,是返回Ture,否则返回 False
print(str.islower())
#isupper 判断是否大写,是返回Ture,否则返回 False
print(str.isupper())
#istitle 判断是否所有单词都是首字母大写,是返回Ture,否则返回 False
print(str.istitle())
#isspace 判断是所有字符都是空白字符,是返回Ture,否则返回 False
print(str.isspace())
#判断是否为标点符号
print(str in string.punctuation)

List(列表)

列表是写在方括号 [] 之间、用逗号分隔开的元素列表。

列表中元素的类型支持数字,字符串、列表。

# 空列表
a = []
b = [1, 2, 3]
c = ['1', '2', '3']
d = [[1, 2, 3], [4, 5, 6]]

列表生成式

# 生成[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`
a = list(range(1, 11))
print(a)
# output [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 生成 100 以内的平方数
b = [x * x for x in range(1, 11)]
print(b)
# output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 生成10以内的偶数
c = [x for x in range(1, 11) if x % 2 == 0]
print(c)
# output: [2, 4, 6, 8, 10]
# 生成10以内奇数加负号
d = [x if x % 2 == 0 else -x for x in range(1, 11)]
print(d)
# output: [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]

常用函数

  1. insert(i, e): Insert integer e at position i.
  2. print: Print the list.
  3. remove(e) : Delete the first occurrence of integer e.
  4. append(e): Insert integer at the end of the list.
  5. sort(): Sort the list.
  6. pop(): Pop the last element from the list.
  7. reverse(): Reverse the list.

排序

#升序
l.sort()
# 降序
l.sort(reverse=True)

list差集、并集和交集实例

a_list = [1,2,3,4]
b_list = [1,4,5]
# 一. 差集
# 很明显结果是[2,3,5],具体方法如下:
# 方法a.正常法:
ret_list = []
for item in a_list:
if item not in b_list:
ret_list.append(item)
# 方法b.简化版:
ret_list = [item for item in a_list if item not in b_list]
#方法c.高级版:
ret_list = list(set(a_list)^set(b_list))
# 二. 并集
# 很明显结果是[1,2,3,4,5], 具体方法如下:
ret_list = list(set(a_list).union(set(b_list)))
#三. 交集
#很明显结果是[1,4],具体方法如下:
ret_list = list((set(a_list).union(set(b_list)))^(set(a_list)^set(b_list)))

Tuple(元组)

元组写在小括号 () 里,元素之间用逗号隔开。

与列表相似,不同之处在于元组的元素不能修改

Set(集合)

使用大括号 { } 或者 set() 函数创建集合

注: 创建一个空集合必须用 set()

常用函数

.add(x)

If we want to add a single element to an existing set, we can use the .add() operation.

It adds the element to the set and returns 'None'.

Example

s = set('HackerRank')
s.add('H')
print(s)
#output: set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
s.add('HackerRank')
print(s)
# output: set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])

.remove(x)

This operation removes element from the set.

If element does not exist, it raises a KeyError.

The .remove(x) operation returns None.

Example

s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
s.remove(5)
print(s)
# output: set([1, 2, 3, 4, 6, 7, 8, 9])
s.remove(0)
# Error: KeyError: 0

.discard(x)

This operation also removes element from the set.

If element does not exist, it does not raise a KeyError.

The .discard(x) operation returns None.

Example

s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
s.discard(5)
print(s)
# output: set([1, 2, 3, 4, 6, 7, 8, 9])
s.discard(0)
print(s)
# output: set([1, 2, 3, 4, 6, 7, 8, 9])

.pop()

This operation removes and return an arbitrary element from the set.

If there are no elements to remove, it raises a KeyError.

Example

s = set([1])
print(s.pop())
# output: 1
print(s)
set([])
print(s.pop())
# Error : KeyError: pop from an empty set

.clear()

This operation clear all element from the set.

.union()

The .union() operator returns the union of a set and the set of elements in an iterable.

Sometimes, the | operator is used in place of .union() operator, but it operates only on the set of elements in set.

Set is immutable to the .union() operation (or | operation).

.intersection()

The .intersection() operator returns the intersection of a set and the set of elements in an iterable.

Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set.

The set is immutable to the .intersection() operation (or & operation).

.difference()

The tool .difference() returns a set with all the elements from the set that are not in an iterable.

Sometimes the - operator is used in place of the .difference() tool, but it only operates on the set of elements in set.

Set is immutable to the .difference() operation (or the - operation).

.symmetric_difference()

The .symmetric_difference() operator returns a set with all the elements that are in the set and the iterable but not both.

Sometimes, a ^ operator is used in place of the .symmetric_difference() tool, but it only operates on the set of elements in set.

The set is immutable to the .symmetric_difference() operation (or ^ operation).

Dictionary(字典)

字典是一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。

键(key)是不可变类型,在同一个字典中,键(key)必须是唯一的。

排序

# 按先key后value排序
res = sorted(dict.items(), key=lambda item:(item[1], item[0]))

迭代器

zip 横向合并

a = [1, 2, 3]
b = [4, 5, 6]
print(list(zip(a, b)))
# ([1, 4], [2, 5], [3, 6])

lambda

def add(x, y):
return x + y
print(add(1, 2))
# 3
add2 = lambda x, y: x+y
print(add2(1, 2)
# 3

map

def add(x, y):
return x + y
print(list(map(add, [1], [2])))
# [3]

函数

定义函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,有返回值用return语句返回

def my_abs(x):
if x >= 0:
return x
else:
return -x

定义类需要使用class关键字,类名通常是大写开头的单词,紧接着是(object)

object表示当前类的父类

class Student(object):
# 初始化
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
def __str__(self):
return "massge that you want to print"

安装及导入模块

使用pip命令安装

导入模块

1.同一目录下,直接导入

2.python安装目录 对应的site_packages目录下

导入模块

import ..

from .. import ..

文件读写

open('file','mode')

参数解释
file:需要打开的文件路径
mode(可选):打开文件的模式,如只读、追加、写入等

mode常用的模式:

  • r:表示文件只能读取

  • w:表示文件只能写入

  • a:表示打开文件,在原有内容的基础上追加内容,在末尾写入

  • w+:表示可以对文件进行读写双重操作

  • rb:以二进制格式打开一个文件,用于只读

  • wb:以二进制格式打开一个文件,用于只写

  • ab:以二进制格式打开一个文件,用于追加

  • wb+:以二进制格式打开一个文件,用于读写

file_path="test.txt"
# 基础版
try:
f = open(file_path, 'r')
print(f.read())
finally:
if f:
f.close()
# 进阶版
with open(file_path, 'r') as f:
# 读取文件全部内容
contents = f.read()
print(contents)
# 按行输出
for line in f:
print(line)

filename = 'write_data.txt'
# 如果filename不存在会自动创建, 'w'表示写数据,写之前会清空文件中的原有数据!
with open(filename,'w') as f:
f.write("I am Meringue.\n")
f.write("I am now studying in NJTECH.\n")

异常、错误处理

try:
file = open('a', 'r+')
# 出错,输出错误信息
except Exception as e:
print(e)
# 正常,执行对应操作
else:
file.write('hello !')
# finally 不管是否出错,都会执行
finally:
file.close()

浅拷贝与深拷贝

a = [1, 2, 3]
b = a
print(id(a))
print(id(b))
# a,b 指向同一个存储地址,
print(id(a) == id(b))
# 浅拷贝:只拷贝第一层
import copy
# 1
c = copy.copy(a)
# a,c 不指向同一个存储地址
print(id(a) == id(c))
# 2
d = [1, 2, [3, 4]]
e = copy.copy(d)
# d,e不指向同一个存储地址
print(id(d) == id(e))
# d,e的子列表指向同一个存储地址
print(id(d[2]) == id(e[2]))
# 深拷贝:完全拷贝
f = copy.deepcopy(d)
# d,e的子列表不指向同一个存储地址
print(id(d[2]) == id(f[2]))

多线程

多核运算

TKinter 窗口

pickle 存放数据

import pickle
a = [1, 2, 3]
# 存储
file = open('pickle_example.pickle', 'wb')
pickle.dump(a, file)
file.close()
# 存储进阶方法
with open('pickle_example.pickle', 'wb') as file:
pickle.dump(a, file)
print("save success!")
# 读取
file = open('pickle_example.pickle', 'rb')
a = pickle.load(file)
print(a)
file.close()
# 读取进阶方法
with open('pickle_example.pickle', 'rb') as file:
a = pickle.load(file)
print(a)

numpy

pandas

plotlib

参考资料

posted @   ZTianming  阅读(99)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
欢迎阅读『Python基础』

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示