python基础总结——列表元组集合字典文件等等

列表

  1. 增删改查

    x = [1, 2, 3]
    # 增加元素
    x.append(4)
    x.insert(-1, 4)
    
    # 删除元素,如果删除元素不再使用就用del
    tail = x.pop() # 弹出末尾元素 注: pop是函数不是语句,括号没提供参数,默认为-1,表示最后一个元素
    head = x.pop(0) # 弹出首元素
    del x[0] # 一般函数后边跟小括号,中括号表示索引, x[0]是x的第一个元素,x[1]是第二个元素,x[-1]是最后一个元素
    
    # remove删除指定元素,删除第一个,列表中可能包含多个相同元素,remove(2)只删除第一个出现的2
    x = [1, 2, 2, 3]
    x.remove(2)
    print(x)
    
    # 删除所有元素
    x.clear()
    
    # 修改元素
    x[0] = 4
    
    # 获取目标的索引, 注:基本所有的编程语言下标都是从0开始,matlab除外
    idx = x.index(3)
    
    # 统计目标的数量
    c = x.count(6)
    
    # 浅拷贝,修改y不影响x
    y = x.copy()
    y.clear()
    print(x, y)
    
  2. 排序

    x = [2, 3, 1, 4]
    # 永久排序
    x.sort() # 单词积累不够哦,sort也是排序的意思
    # x.sort()表示对x进行排序,不返回任何值
    
    # 临时排序
    y = sorted(x) # sorted是个函数,将x作为输入,返回排序后的结果
    
    # 降序排序
    y = sorted(x, reverse=True) # True和False是python里面的布尔值,预先定义好的,把True赋值给变量reverse,表示执行降序,为False则不执行,这两个值可以理解为yes和no
    
    # 按规则排序
    y = sorted(x, key=lambda x: 10-x)
    
  3. 逆序

    x = list(range(10))
    # 永久逆序
    x.reverse()
    
    # 临时逆序 1
    tmp = reversed(x) # tmp是迭代器
    
    # 迭代器转列表
    tmp = list(tmp)
    tmp = [i for i in tmp]
    
    # 临时逆序 2
    y = x[::-1]
    
    # 遍历迭代器
    for i in tmp:
        print(i)
    
    
  4. 创建空列表/元组/集合/字典

    # 创建空列表
    x = []
    x = list()
    
    # 空元组
    x = ()
    x = tuple()
    
    # 创建一个元素的元组
    x = (1, )	# (1)
    x = (1)		# 1
    
    # 创建空字典
    x = {}
    x = dict()
    
    # 创建空集合
    x = set()
    

元组

# 主要方法
x = tuple(range(10))
c = x.count(3)
idx = x.index(3)

集合

  1. 增删改查

    x =	set(range(10))
    
    # 添加元素,如果已存在不受影响
    x.add(3)
    
    # 清空集合
    x.clear()
    
    # 浅拷贝
    y = x.copy()
    
    # 删除元素
    head = x.pop()
    x.remove(3)
    
    
  2. 集合运算

    x = set(range(10))
    y = set(range(5, 14))
    # 交集
    i = x & y
    i = x.intersection(y)
    
    # 并集
    u = x | y
    u = x.union(y)
    
    # 差集
    s = x - y
    s = x.difference(y)
    
    # 子集
    s.issubset(x)	# s是x的子集
    x.issuperset(s)	# s是x的子集吗
    
    # 两个集合有无交集
    x.isdisjoint(y)
    

字典

  1. 创建字典

    x = {1: 2, 2: 3}
    # zip
    a = range(10)
    b = range(1, 11)
    x = dict(zip(a, b))
    
  2. 遍历字典

    for k, v in x.items():
        print(k, v)
        
    keys = x.keys()
    values = x.values()
    
    
  3. 增删改查

    x = dict(zip('1234', 'zero'))
    
    # 删除指定key的元素
    v = x.pop('2')	# z
    
    # 删除末尾元素
    kv = x.popitem() # (4, 'o')
    
    # 获取指定元素
    v = x.get('1')	# z,不存在则返回None
    v = x['1']		# 不存在则出错
    
    # 添加元素
    x['5'] = -1
    
    

字符串

  1. 大小写转换

    x = "zero"
    # 小写转大写
    x = x.upper()
    # 大写转小写
    x = x.lower()
    # 首字母大写
    x = x.title()
    x = x.capitalize()
    
    
  2. startswith和endswith

    x = "zero.jpg"
    s = x.startswith('zero')
    e = x.endswith('jpg')
    
    
  3. 查找子串

    x = "zero.jpg"
    # 返回开始匹配的索引,从右边查找使用rfind/rindex
    idx = x.find('er') # 1,不存在则返回-1
    idx = x.index('er')	# 1, 不存在则报错
    
    # 判断是否是子串
    issub = x.find('er')!=-1
    issub = 'er' in x
    
    
  4. 字符串成分

    x = "zero"
    # 字符串全是数字
    print(x.digit())
    
    # 字符串全是字母
    print(x.isaplha())
    
    # 字符串只有字母和数字
    print(x.isalpha())
    
    # 字符串字符全是ascii
    print(x.isascii())
    
    # 字符串全是小写/大写字符
    print(x.islower())
    print(x.isupper())
    
    # 字符串全是空白符
    print(x.isspace())
    
    
  5. 删除空白符

    x = '\nzero\n'
    # 删除左右空白符
    print(x.lstrip())
    print(x.rstrip())
    print(x.strip('\n'))
    
    
  6. 分割和替换

    x = 'zero.jpg'
    # 分割
    print(x.split('.'))
    # 替换
    print(x.replace('.', ' '))
    
    

if

可以不使用else,也可以可以不适用elif

文件读写和错误处理

  1. 读文件

    # 一次读取全部,文件比较大时不推荐使用
    with open('zero.txt', "r") as f:
        content = f.read()
        
    # 逐行读取 1,文件比较大时不推荐使用
    with open('zero.txt', "r") as f:
        lines = f.readlines()	# lines是列表
        
    # 逐行读取 2,推荐使用
    with open('zero.txt', "r") as f:
        for line in f:
            print(line)
            
    # 逐行读取 3,推荐使用
    with open('zero.txt', "r") as f:
        line = f.readline()
        while line:
            print(line)
            line = f.readline()
    
    
  2. 写文件

    # 逐行写入
    with open('zero.txt', "w") as f:
        f.write('zero, hello\n')
        f.write('hello\n')
        
    # 末尾添加
    with open('zero.txt', "a") as f:
        f.write('hello\n')
    
    
  3. 错误处理

    # try-except-else
    try:
        res = requests.get(url)
    except Exception as e:
        print(e)
    else:
        print('executed successed')
    
    
  4. json读写信息

    x = dict(zip("zero", "1234"))
    # 将变量存储到json字符串中
    y = json.dumps(x)
    
    # 将json字符串转为python对象
    z = json.loads(y)
    
    # 变量到json文件
    with open('zero.json', "w") as f:
        json.dump(x, f)
        
    # 从json读取变量
    with open('zero.json', "r") as f:
        y = json.load(f)
        
    
    
  5. 读写csv

    import csv
    
    # 读取csv
    with open('zero.csv') as f:
        reader = csv.reader(f, delimiter=',')
        next(reader)	# 获取表头
        for line in reader:
         print(line)
            
    # 列表写入文件
    with open('one.csv', "w", newline="") as f:
        writer = csv.writer(f)
        for row in lines:
            writer.writerow(row)
    
    
    

栈和队列

  1. 列表作栈

    stack = [1, 2, 3, 4]
    # 入栈
    stack.append(5)
    print(stack)
    
    # 出栈
    stack.pop()
    print(stack)
    
    # 栈顶元素
    print(stack[-1])
    
    # 栈空
    print(len(stack)==0)
    
    
  2. 双端队列

    from collections import deque
    
    queue = deque([1, 2, 3, 4])
    # 入队
    queue.append(5)		# 还有appendleft()
    print(queue)
    
    # 出队
    x = queue.popleft() # pop() 弹出右端元素
    print(x)
    
    # 队列为空
    print(len(queue))
    
    # 创建空队列
    queue = deque()
    
    # extend/extendleft
    queue.extend([5, 6])
    queue.extendleft([5, 6])
    
    # 双端队列也可以作栈使用
    
    
    
  3. 单向队列

    import queue
    
    q = queue.Queue(maxsize=1)
    # 队列空
    print(q.empty())
    
    # 入队
    q.put(1)
    
    # 队满
    print(q.full())
    print(q.qsize())
    
    # 出队
    print(q.get())
    print(q.qsize())
    
    

序列解包

  1. zip循环

    x = list(range(10))
    y = list(range(1, 11))
    for k, v in zip(x, y):
        print(k, v)
    
    
  2. zip

    x = [1, 2, 3]
    y = [2, 3 ,5]
    z = list(zip(x, y))
    print(z)
    
    x, y = zip(*z)
    print(x, y)
    
    

collections

  1. Counter

    Counter类继承dict类, 因此可以使用字典中的方法

    import collections
    
    # 统计字符串
    x = collections.Counter('aabbccdddd')
    print(x)
    
    # 统计频数最多的元素
    print(x.most_common(2))
    
    # 初始化Counter
    x = collections.Counter()			# 空Counter
    x = collections.Counter(a=1, b=2)	# 字典初始化方法
    x = collections.Counter({'a': 1, 'b': 2})
    
    # 打印所有元素
    y = x.elements()	# 可迭代对象
    for i in y:
        print(i)
       
    # 列表化所有元素
    print(list(x.elements()))
    
    # items
    print(x.items())
    for k, v in x.items():
        print(k, v)
        
    # 增加元素
    x = collections.Counter()
    x['a'] = 2	# 字典中的方法
    x.update(['b', 'c'])
    print(x)
    
    # 删除元素
    x.subtract(['a', 'b'])
    print(x)
    
    # Counter之间运算
    x = collections.Counter(a=2, b=3)
    y = collections.Counter(b=2, c=4)
    print(x + y)
    print(x - y)
    x.update(y)		# 字典中的方法
    x.subtract(y)
    
    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值